How to find Array length inside the Handlebar templates?

JavascriptTemplateshandlebars.js

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

My Bad....

{{array.length}} actually worked inside the template. Should have checked/tested it before posting it here.

Solution 2 - Javascript

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>

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbhidevView Question on Stackoverflow
Solution 1 - JavascriptAbhidevView Answer on Stackoverflow
Solution 2 - JavascriptKevin PowellView Answer on Stackoverflow
Solution 3 - JavascriptgesiudView Answer on Stackoverflow
Solution 4 - JavascriptEpirocksView Answer on Stackoverflow