Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars lookup in array

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)?

like image 733
Bet Avatar asked Aug 11 '26 13:08

Bet


1 Answers

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}}
like image 70
Luggage Avatar answered Aug 13 '26 04:08

Luggage