我正在使用 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}}
我可以在没有 helper 的情况下这样做吗?以下是我的尝试。我也尝试过使用 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}}
最佳答案
我为此创建了一个解决方案,我不知道它有多好,但它运行良好
试试这个:)
{{#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}}
关于javascript - 使用循环索引访问 Handlebars 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49616221/