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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With