【问题标题】:Handlebars, write two variables into the select box, one in select opt and another one as optionsHandlebars,将两个变量写入select框,一个在select opt中,另一个作为options
【发布时间】:2017-10-24 00:57:44
【问题描述】:

晚上好,我正在做一个项目,我从 JSON 或 Object 的 api 获取数据。 在第一个变量中,我获得了成就的类别,在另一个变量中,我获得了成就,我想要做的是我有一个选择框,其中类别作为 optgroup,选项作为成就。这是我的代码

<select>
    {{#each test}}
        <optgroup label="{{this}}"></optgroup>
        {{#each test2}}
        <option>{{this}}</option>
        {{/each}}
    {{/each}}
</select>

【问题讨论】:

    标签: javascript node.js mongodb api handlebars.js


    【解决方案1】:

    根据MDN docs&lt;optgroup&gt; 应该将其包装为&lt;option&gt;

    此外,由于 test 中的每个项目看起来都是一个字符串(您使用 {{this}} 作为标签值),您需要使用 ../test2@root notation 。这当然是假设这个数据结构:

    {
      test: ['category1', 'category2'],
      test2: ['achievement1', 'achievement2', 'achievement3', 'achievement4']
    }
    

    但是,这种模式没有意义,对于test 中的每个项目,您会看到test2 的相同列表。因此,下面的代码将采用这种数据结构,其中每个类别都显示了它的具体成就:

    {
      test: [{
        label: 'category1'
        test2: ['achievement1', 'achievement2']
      }, {
        label: 'category2'
        test2: ['achievement3', 'achievement4']
      }]
    }
    

    代码:

    <select>
      {{#each test}}
        <optgroup label="{{this.label}}">
          {{#each test2}}
            <option>{{this}}</option>
          {{/each}}
        </optgroup>
      {{/each}}
    </select>
    

    简而言之,您:

    1) 需要将&lt;option&gt; 包装在各自的&lt;optgroup&gt;

    2) 需要修复:

    a) 使用../test2@root/test2test2 列表访问范围(假设每个test 都是一个字符串)

    b) 使用{{this.label}} 访问optgroup 标签的方式(假设每个test 是一个以labeltest2 为属性的对象)

    【讨论】:

      猜你喜欢
      • 2013-01-17
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多