admin管理员组文章数量:1144511
I have a Handlebars template which is rendered using a json object. In this json I am sending an array. Like this:
var json = {
"array":["abc","def","ghi","jkl"]
}
Now in my template I want to find the length of this array. Something like:
{{#each item}}
{{ array.length }}
{{/each}}
Couldn't find it in the Handlebars documentation.
I have a Handlebars template which is rendered using a json object. In this json I am sending an array. Like this:
var json = {
"array":["abc","def","ghi","jkl"]
}
Now in my template I want to find the length of this array. Something like:
{{#each item}}
{{ array.length }}
{{/each}}
Couldn't find it in the Handlebars documentation.
Share Improve this question edited Sep 18, 2015 at 20:17 celeritas 2,2811 gold badge19 silver badges28 bronze badges asked Mar 15, 2013 at 9:19 AbhidevAbhidev 7,2536 gold badges22 silver badges26 bronze badges4 Answers
Reset to default 234My Bad....
{{array.length}}
actually worked inside the template. Should have checked/tested it before posting it here.
In this case you need to reference the parent variable of the each from within the each block:
{{#each array}}
{{../array.length}}
{{/each}}
I think your variable being named "array" is probably conflating the issue as well. Let's assume some different JSON just to clarify:
var json = {
"fruit":["apple","orange","banana"]
};
So then doing this:
<ul>
{{#each fruit}}
<li>{{this}} {{@index}} {{../fruit.length}}</li>
{{/each}}
</ul>
Would yield:
<ul>
<li>apple 0 3</li>
<li>orange 1 3</li>
<li>banana 2 3</li>
</ul>
You can define simple helper to handle it:
Handlebars.registerHelper('get_length', function (obj) {
return obj.length;
});
And then use it in your template eg:
{{get_length some_object}}
If you are testing for an empty list in order to display content... In Ember.js which uses handlebars, you can have an else for the #each.
{{#each blah as |blah|}}
{{else}}
// If array is empty
{{/each}}
本文标签: javascriptHow to find Array length inside the Handlebar templatesStack Overflow
版权声明:本文标题:javascript - How to find Array length inside the Handlebar templates? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736830986a1954694.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论