Dmitry Poroh
Dmitry Poroh

Reputation: 3825

Dynamic paths in handlebars

I searched through a lot of questions but hasn't found answer. I use handlebars templates and have data structure:

{
  privileged_users: [ "user1", "user2" ],
  users: {
    user1: { name: "N1" },
    user2: { name: "N2" },
    user3: { name: "N3" }
  }
}

I wan't to output all privileged users with some template. Something like this:

<table>
  {{#each privileged_users}}
     <tr><td>{{../users.[this].name}}</td></tr>
  {{/each}}
</table>

Is it possible without additional helpers?

If it isn't how can I write block helper with changing context to ../users.[this] ?

Upvotes: 1

Views: 1542

Answers (1)

AimZ
AimZ

Reputation: 536

Register following helper:

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

Then modify the template like:

<table>
  {{#each privileged_users}}
     <tr><td>{{lookupProp ../users this 'name'}}</td></tr>
  {{/each}}
</table>

Here is the working fiddle. Previous one is just a simple expression helper.

Now here is a working jsfiddle according to question.

Handlebars has a built-in lookup helper since version 3.0.3. An alternate to block helper could be Handlebars Partial Context approach i.e. define/register a partial and use it with different context in main template.

Upvotes: 2

Related Questions