使用 Handlebars 和 Node,我有一个长度不断变化的数组,每次它发生变化时我都需要获取最后一个元素之前的元素。
所以如果你想得到最后一个元素,你可以这样做:
{{#each array}}
{{#if @last}}
{{this}}
{{/if}}
{{/each}}
它会返回最后一个元素。 我有数学助手,可以执行基本的数学运算。 例如,我可以获得所需的索引号
{{math array.length '-' 1}}
但我不能将它与另一个 block 助手一起使用,例如:
{{#each array}}
{{#if math @last '-' 1}}
{{this}}
{{/if}}
{{/each}}
这怎么可能?谢谢。
最佳答案
您可以为此注册自己的助手:
Handlebars.registerHelper('isSecondLastArrayItem', function(array, index, options) {
if((array.length - 2) === index)
return options.fn(this);
return;
});
然后像这样使用它:
{{#each array}}
{{#isSecondLastArrayItem @root.array @index}}
{{title}}
{{/isSecondLastArrayItem}}
{{/each}}
示例数据:
{
array: [{ title: 'aa' }, { title: 'vv' }]
}
在 sandbox 中试用.
编辑:任何索引的大小写
Handlebars.registerHelper('isNthLastArrayItem', function(array, index, offset, options) {
if(((array.length >= offset) && (array.length - offset) === index)
return options.fn(this);
return;
});
用法(对于末尾的 2nd
项):
{{#each array}}
{{#isNthLastArrayItem @root.array @index 2}}
{{title}}
{{/isNthLastArrayItem}}
{{/each}}
关于javascript - 如果长度未知, Handlebars 返回具有特定索引的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46897761/