我在我的项目中使用模版把手。是否有一种方法可以获得句柄中“each”helper的当前迭代的索引?

<tbody>
     {{#each item}}
         <tr>
            <td><!--HOW TO GET ARRAY INDEX HERE?--></td>
            <td>{{this.key}}</td>
            <td>{{this.value}}</td>
         </tr>
     {{/each}}
</tbody>

当前回答

在车把版4.0以后,

{{#list array}}
  {{@index}} 
{{/list}}

其他回答

这在新版本的烬中有所改变。

数组:

{{#each array}}
    {{_view.contentIndex}}: {{this}}
{{/each}}

看起来#each块不再适用于对象。我的建议是为它滚动您自己的helper函数。

谢谢你的建议。

在Handlebars的新版本中,索引(或对象迭代情况下的键)默认由标准的each helper提供。


片段来自:https://github.com/wycats/handlebars.js/issues/250#issuecomment-9514811

当前数组项的索引已经通过@index可用一段时间了:

{{#each array}}
    {{@index}}: {{this}}
{{/each}}

对于对象迭代,使用@key代替:

{{#each object}}
    {{@key}}: {{this}}
{{/each}} 

在车把版4.0以后,

{{#list array}}
  {{@index}} 
{{/list}}

数组:

{{#each array}}
    {{@index}}: {{this}}
{{/each}}

如果你有对象数组……你可以遍历子节点:

{{#each array}}
    //each this = { key: value, key: value, ...}
    {{#each this}}
        //each key=@key and value=this of child object 
        {{@key}}: {{this}}
        //Or get index number of parent array looping
        {{@../index}}
    {{/each}}
{{/each}}

对象:

{{#each object}}
    {{@key}}: {{this}}
{{/each}} 

如果你有嵌套对象,你可以访问父对象的键 {{@ . . /关键}}

在hbs中使用循环有点复杂

<tbody>
     {{#each item}}
         <tr>
            <td><!--HOW TO GET ARRAY INDEX HERE?--></td>
            <td>{{@index}}</td>
            <td>{{this}}</td>
         </tr>
     {{/each}}
</tbody>

了解更多