Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 750
Mathieu Marques Avatar asked Dec 31 '25 04:12

Mathieu Marques


1 Answers

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

like image 70
esthepiking Avatar answered Jan 04 '26 17:01

esthepiking



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!