95

我有一个使用 json 对象呈现的 Handlebars 模板。在这个 json 中,我发送了一个数组。像这样:

var json = {
               "array":["abc","def","ghi","jkl"] 
}

现在在我的模板中,我想找到这个数组的长度。就像是:

{{#each item}}
   {{ array.length }}
{{/each}}

在 Handlebars 文档中找不到它。

4

4 回答 4

206

我的错....

{{array.length}}实际上在模板内工作。应该在将其发布到此处之前对其进行检查/测试。

于 2013-03-15T09:24:32.050 回答
46

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>
于 2015-04-07T21:06:47.077 回答
2

如果您正在测试一个空列表以显示内容...在使用把手的 Ember.js 中,您可以为 #each 设置一个 else。

{{#each blah as |blah|}}

{{else}}
 //   If array is empty
{{/each}}
于 2018-12-20T09:59:32.427 回答
2

您可以定义简单的助手来处理它:

Handlebars.registerHelper('get_length', function (obj) {
 return obj.length;
});   

然后在您的模板中使用它,例如:

{{get_length some_object}}
于 2016-06-30T11:25:06.657 回答