Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars dynamic property lookup in each loop

In Handlebars 2+, how do I dynamically read a property in a loop like this? objects is an array of objects. keys is an array of strings. I want to loop each key for each object and put the its .foo value in the span.

{{#each objects}}
    {{#each keys}}
        <span>{{../this.{{this}}.foo}}</span>
    {{/each}}
{{/each}}

Is this possible in plain Handlebars 2+? Or...is there a helper that does this?

like image 445
ryanve Avatar asked Apr 28 '15 20:04

ryanve


1 Answers

I don't see the way how it can be done without helper.
With helpers everything is possible (but kind of ugly) in Handlebars.

For example, you could use something like this:

{{#each objects}}
    {{#each keys}}
        <span>{{lookupProp ../this this 'foo'}}</span>
    {{/each}}
{{/each}}

And helper:

Handlebars.registerHelper('lookupProp', function (obj, key, prop) {
   return obj[key] && obj[key][prop];
});

Look at the fiddle.

Handlebars has built-in lookup helper since version 3.0.3.

like image 118
raidendev Avatar answered Oct 06 '22 19:10

raidendev