ryanve
ryanve

Reputation: 52601

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?

Upvotes: 7

Views: 12006

Answers (3)

Gerardlamo
Gerardlamo

Reputation: 1723

For anyone else that doesn't want to loop you could use with eg.

{{#with (lookup myObject myKeyVar) as |subObject|}}
  {{subObject.key}}
{{/with}}

Upvotes: 6

ShQ
ShQ

Reputation: 776

Okay... spent a few hours googling around and find a nice solution, as I had the same issue, but failed to find any...

I was as happy as Larry and jumped off my chair when I finally figured a way to get this working :D

This way, you can access object values with dynamic keys,

Demo object:

var categories = {
    onion: { name: 'bar', id: 4 }, 
    apple: { name: 'demo', id: 2 }, 
    carrot: { name: 'foo', id: 3 }, 
    Root: [
        { name: 'apple' },
        { name: 'onion' },
        { name: 'carrot' }
    ]
};

Instead of trying something like these: (which won't work)

{{#each categories.[@key]}} 
or
{{#each categories.[mykey]}}

You can do:

{{#each categories.[Root] as |main-category|}}

    {{#each (lookup ../categories main-category.name) as |sub-category|}}

        {{sub-category.name}}

    {{/each}}

{{/each}}

Hope it will help for someone else too :)

Upvotes: 7

raidendev
raidendev

Reputation: 2809

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.

Upvotes: 8

Related Questions