Mathieu Marques
Mathieu Marques

Reputation: 1748

How do I access an array content using {{this}} inside a Handlebars loop?

I am currently using Handlebars to dynamically populate some panels. In one of them, I feel the need of repeating a given task.

// Add a looping helper for Handlebars
Handlebars.registerHelper('repeat', function(nFrom, nTo, oBlock) {
    var sResult = '';
    for (var i=nFrom; i < nTo+1; i++)
        sResult += oBlock.fn(i);
    return sResult;
});
{{#if oSomeObject}}
<ul>
    {{# repeat 1 2}}
    <li>{{../oSomeObject.aSomeProperty[{{this}}]</li>  <!-- Does not work (because of nested curlies) -->
    <li>{{../oSomeObject.aSomeProperty[this]}}</li>  <!-- Does not work -->
    {{/repeat}}
</ul>
{{/if}}

Is there any known way for me to access my array's content within my repeat block ?

Upvotes: 3

Views: 787

Answers (1)

esthepiking
esthepiking

Reputation: 1647

I would do it like this:

Handlebars.registerHelper('myHelper', function(object, nFrom, nTo, oBlock){
    var sResult = '';
    for(var i=nFrom; i<nTo+1; i++)
        sResult += oBlock.fn(object[i]);
    return sResult;
});

or, if you want to iterate though all of the oSomeObject's

Handlebars.registerHelper('myHelper', function(object, oBlock){
    var sResult = '';
    for(var i=0; i<object.length; i++)
        sResult += oBlock.fn(object[i]);
    return sResult;
});

then you can call it with:

{{#myHelper oSomeObject}}
    <li>{{aSomeProperty}}</li>
{{/myHelper}}

this is in effect the same as handlebars' each block helper, so you could use just:

{{#each oSomeObject}}
    <li>{{aSomeProperty}}</li>
{{/each}}

source

Upvotes: 1

Related Questions