gpt4 book ai didi

templates - Handlebars 模板 - 添加递增变量的最佳方法

转载 作者:行者123 更新时间:2023-12-03 11:52:46 25 4
gpt4 key购买 nike

我想使用 Handlebars 模板在表格中添加一个计数器。我有一个像这样的 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>

这可行,但变量 i 不增加,解决此问题的最佳方法是什么?

最佳答案

您可以使用 {{@index}} 访问当前索引

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

但是这个 index 会以 0 开头,这有时你可能不想要。

在这种情况下,您可以创建和注册帮助方法来增加索引。

Handlebars.registerHelper("inc", function(value, options)
{
return parseInt(value) + 1;
});

然后您可以使用 inc 关键字在 Handlebars 表达式中使用它,例如:

{{inc @index}}

但如果你不想这样做,还有另一种更简单的方法可以达到同样的效果。

{{@index_1}}

试一试。

关于templates - Handlebars 模板 - 添加递增变量的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28007899/

25 4 0