How to find Array length inside the Handlebar templates?

风流意气都作罢 提交于 2019-12-02 18:40:25
Abhidev

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

try this:

   {{#each item}}
   {{ json.array.length }}
{{/each}}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!