I have JSON object:
{
groups: [
{id: 1, title: "group1"},
{id: 2, title: "group2"},
],
users: [
{id:1, login: "user1", groupId: 1},
{id:2, login: "user2", groupId: 2},
{id:3, login: "user3", groupId: 1}
]
}
and handlebars template:
{{#each users}}
<tr data-id="{{id}}">
<td>{{login}}</td>
<td data-id="{{groupId}}">{{lookup ../groups groupId}}{{title}}</td>
</tr>
{{/each}}
but it is not working. Template compile and table render, but table group column contains only id as attribute of td tag. How to render title of group inside td tag (it is possible with handlebars using this JSON object)?
The lookup helper only looks up by array index, not but an id, but you can whip up a helper to do that:
Handlebars.registerHelper('lookup2', function(collection, id) {
var collectionLength = collection.length;
for (var i = 0; i < collectionLength; i++) {
if (collection[i].id === id) {
return collection[i];
}
}
return null;
});
Then you'll need to lookup the title from that object. Here I use #with to change context:
{{#each users}}
<tr data-id="{{id}}">
<td>{{login}}</td>
<td data-id="{{groupId}}">{{#with (lookup2 ../groups groupId)}}{{title}}{{/with}}</td>
</tr>
{{/each}}
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