我使用handlebars.js迭代categories
,然后使用当前数组索引访问series
数组中的元素。我可以使用下面的帮助器来完成。
var json={
"categories": [{
"id": 3,
"name": "category 0"
}, {
"id": 6,
"name": "category 1"
}
],
"series": [{
"id": 1,
"name": "DUMMY",
"data": [{
"id": 5,
"name": "series 0 data 0"
}, {
"id": 10,
"name": "series 0 data 1"
}
]
}
]
}
Handlebars.registerHelper('getArrayValues', function(ar, index, prop) {
return ar[0].data[index][prop];
});
var template = Handlebars.compile(json);
{{#each categories}}
<p>id: {{this.id}}</p>
<p>name: {{this.name}}</p>
<p>series id with helper: {{getArrayValues ../series @index 'id' }}</p>
<p>series name with helper: {{getArrayValues ../series @index 'name' }}</p>
{{/each}}
我能在没有助手的情况下这样做吗?以下是我的尝试。我还尝试使用lookup
,但似乎可以访问lookup
返回的属性。
{{#each categories}}
<p>id: {{this.id}}</p>
<p>name: {{this.name}}</p>
<p>series id: {{../series.[0].data.[@index].id}}</p>
<p>series name: {{../series.[0].data.[@index].name}}</p>
{{/each}}
答案 0 :(得分:1)
我为此创立了一个解决方案,我不知道它有多好,但它工作得很好
试试这个:)
{{#each categories}}
<p>id: {{this.id}}</p>
<p>name: {{this.name}}</p>
<p>series id with helper:{{#with (lookup ../series.[0].data
@index) }}{{this.id}}{{/with}}</p>
<p>series name with helper: {{#with (lookup ../series.[0].data
@index) }}{{this.name}}{{/with}}</p>
{{/each}}