105

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.

celeritas
  • 2,191
  • 1
  • 17
  • 28
Abhidev
  • 7,063
  • 6
  • 21
  • 26

4 Answers4

226

My Bad....

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

Stéphane Bruckert
  • 21,706
  • 14
  • 92
  • 130
Abhidev
  • 7,063
  • 6
  • 21
  • 26
50

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>
Kevin Powell
  • 596
  • 5
  • 7
3

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}}
gesiud
  • 106
  • 5
  • 2
    `length` is a property of the object, it's not necessary to register helpers to get the value of a property since Handlebars supports dot notation. – Paul Aug 05 '21 at 12:28
2

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}}
Epirocks
  • 480
  • 4
  • 11