在HandlebarsJS中迭代{{#each}}若干次



我在HandlebarsJS中有以下代码:

<thead>
<tr>
{{#each this.attr_name}}
{{#if @index < 9}}
<th>{{ this }}</th>
{{/if}}
{{/each}}
</tr>
</thead>

但是这条线{{#if @index < 5}}不工作。我想迭代{{#each8次。

Handlebars没有任何内置的方法来做@index < 9的比较逻辑。您需要创建自己的自定义助手来完成此操作。

幸运的是,您的问题可以通过一个非常简单的帮助来解决。

例如,实现@index < 9比较,您可以创建一个助手,它接受一些数字num和比较数字comparator,如果num < comparatorfalse,则返回true:

Handlebars.registerHelper('lessThan', (num, comparator) => num < comparator);

要在模板中实现这个帮助器:

{{#each this.attr_name}}
{{#if (lessThan @index 8)}}
<th>{{ this }}</th>
{{/if}}
{{/each}}

注意:我们使用8作为comparator参数,而不是9,因为你的问题说你想输出8个项目,@index是基于0的,所以:0,1,2,3,4,5,6,7是8个项目。

这是一个小提琴的例子。

另一种方法是创建一个助手,它接受一个数组和一个count,并返回该数组中第一个count项数:

Handlebars.registerHelper('first', (arr, count) => arr.slice(0, count));

在你的模板中使用这个帮助可以简化为:

{{#each (first this.attr_name 8)}}
<th>{{ this }}</th>
{{/each}}

下面是演示这种方法的小提琴。

最新更新