javascript 如何在 Handlebar 模板中找到数组长度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15428584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find Array length inside the Handlebar templates?
提问by Abhidev
I have a Handlebars template which is rendered using a json object. In this json I am sending an array. Like this:
我有一个使用 json 对象呈现的 Handlebars 模板。在这个 json 中,我发送了一个数组。像这样:
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.
在 Handlebars 文档中找不到它。
回答by Abhidev
My Bad....
我的错....
{{array.length}}
actually worked inside the template. Should have checked/tested it before posting it here.
{{array.length}}
实际上在模板内工作。在这里发布之前应该检查/测试它。
回答by Kevin Powell
In this case you need to reference the parent variable of the each from within the each block:
在这种情况下,您需要从 each 块中引用 each 的父变量:
{{#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:
我认为你的变量被命名为“数组”也可能混淆了这个问题。让我们假设一些不同的 JSON 来澄清:
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>
回答by gesiud
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}}
回答by Epirocks
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.
如果您正在测试一个空列表以显示内容...在使用把手的 Ember.js 中,您可以为 #each 设置一个 else。
{{#each blah as |blah|}}
{{else}}
// If array is empty
{{/each}}