我有JSON对象:
{
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}
]
}
和把手模板:
{{#each users}}
<tr data-id="{{id}}">
<td>{{login}}</td>
<td data-id="{{groupId}}">{{lookup ../groups groupId}}{{title}}</td>
</tr>
{{/each}}
但它不起作用。模板编译和表呈现,但表组列仅包含id作为td标记的属性。如何在td标签内呈现组的标题(使用此JSON对象可以使用把手)?
答案 0 :(得分:1)
lookup
帮助程序只按数组索引查找,而不是id,但你可以启动帮助程序来执行此操作:
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;
});
然后你需要从该对象中查找标题。在这里,我使用#with
来更改上下文:
{{#each users}}
<tr data-id="{{id}}">
<td>{{login}}</td>
<td data-id="{{groupId}}">{{#with (lookup2 ../groups groupId)}}{{title}}{{/with}}</td>
</tr>
{{/each}}