如何在句柄条模板中查找数组长度?

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

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

现在在我的模板中,我想找到这个数组的长度,比如:

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

在车把上找不到。

97990 次浏览

My 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}}