How to find Array length inside the Handlebar templates? How to find Array length inside the Handlebar templates? javascript javascript

How to find Array length inside the Handlebar templates?


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