嵌套每个条件if

时间:2019-10-09 15:46:15

标签: handlebars.js mustache

这是我的对象数组。我试图使用车把来创建类似这样的输出。我该如何实现?甚至可以使用把手。

var employee=[
           {name: "Ahmed", position: "head"},
           {name: "Matt", position: "TA"},
           {name: "Tai", position: "head"},
           {name: "Buddy", position: "instructor"},
           {name: "Collin", position: "instructor"}
       ]

   * Ahmed
   * Tai

讲师

    * Buddy
    * Collin

TA

    * Matt

我可以使用#each帮助程序来打印名称

<ul class="people_list">
  {{#each people}}
    <li id="{{this.name}}">{{this.name}}</li>
  {{/each}}
</ul>

更新:

所以我已经更新了代码,但仍然无法正常工作

var employeeObject=employeeTemp
var context={people:employeeObject}
var html=template(context)

这是车把模板

   {{#each people}}
    <h2>{{@key}}</h2>
    <ul class="people_list">
        {{#each this}}
            <li id="{{this.name}}">{{ this.name }}</li>
        {{/each}}
    </ul>
{{/each}}

1 个答案:

答案 0 :(得分:0)

创建一个助手array来收集position的数据

var employee=[
  {name: "Ahmed", position: "head"},
  {name: "Matt", position: "TA"},
  {name: "Tai", position: "head"},
  {name: "Buddy", position: "instructor"},
  {name: "Collin", position: "instructor"}
];

var employeeTemp = [];

for(var e of employee) {
  if(!employeeTemp[e.position])
    employeeTemp[e.position] = [];
    employeeTemp[e.position].push(e);
}

employee = employeeTemp;

车把:

{{#each employee}}
    <h2>{{@key}}</h2>
    <ul class="people_list">
        {{#each this}}
            <li id="{{this.name}}">{{ this.name }}</li>
        {{/each}}
    </ul>
{{/each}}