Ale*_*lls 3 templates handlebars.js
我想使用 Handlebars 模板在表格中添加一个计数器。我有一个把手模板,如下所示:
<script type="text/template" id="user-home-main-table-template">
<% var i=0 %>
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Team Name</th>
<th>Club</th>
<th>Sport</th>
<th>Delete?</th>
</tr>
</thead>
<tbody>
{{#teams}}
<tr>
<td><%=i%></td>
<td>{{teamName}}</td>
<td>{{club}}</td>
<td>{{sport}}</td>
<td>delete</td>
</tr>
{{/teams}}
</tbody>
</table>
</script>
Run Code Online (Sandbox Code Playgroud)
这可行,但变量 i 不增加,解决这个问题的最佳方法是什么?
您可以使用{{@index}}来访问当前索引
{{#each array}}
{{@index}}: {{this}}
{{/each}}
Run Code Online (Sandbox Code Playgroud)
但这个索引将从0开始,有时您可能不希望这样。
在这种情况下,您可以创建并注册辅助方法来增加索引。
Handlebars.registerHelper("inc", function(value, options)
{
return parseInt(value) + 1;
});
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用关键字在车把表达式中使用它inc,例如:
{{inc @index}}
Run Code Online (Sandbox Code Playgroud)
但如果您不想这样做,还有另一种更简单的方法可以实现相同的目的。
{{@index_1}}
Run Code Online (Sandbox Code Playgroud)
试一试。