在Handlebars模板中获取JSON数组的最后一个元素 [英] Getting the last element from a JSON array in a Handlebars template
问题描述
{{myArray.2.nestedObject}}和{{myArray.0.nestedObject}}
..以获得第三个和第一个元素。 ( handlebars-access-array-item )
有没有办法从数组中获取最后一个元素?
我试着为它创建一个帮助器:
Handlebars.registerHelper(lastElement,function(array){
return array.last(); //Array.prototype extension
});
...并在模板中按如下方式调用它:
{{lastElement myArray}}甚至{{lastElement myArray.lastElement nestedArray}}
可悲的是,这是行不通的。显然,Helper函数会返回字符串。我需要的是一种即使对于多维数组也能做到这一点的方法。
我应该工作,
$ b
模板:
数据:
{foo:[1,2,3,4,5,6]}
Helper:
$ p $ Handlebars.registerHelper(last,function(array){
return array [array.length -1];
});
So, I found that array elements can be accessed in Handlebars using:
{{myArray.2.nestedObject}} and {{myArray.0.nestedObject}}
..to get the third and first elements for instance. (handlebars-access-array-item)
Is there a way to get the last element from an array? I tried creating a helper for it:
Handlebars.registerHelper("lastElement", function(array) {
return array.last(); //Array.prototype extension
});
...and calling it as follows in the template:
{{lastElement myArray}} or even {{lastElement myArray.lastElement nestedArray}}
Sadly, this doesn't work. Helper functions return strings apparently. What I need is a way to be able to do this even with multi-dimensional arrays.
Should work, I've tested it.
Template:
{{last foo}}
Data:
{foo : [1,2,3,4,5,6]}
Helper:
Handlebars.registerHelper("last", function(array) {
return array[array.length-1];
});
这篇关于在Handlebars模板中获取JSON数组的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!