我有一个看起来像这样的对象:
Cards : [{
Object1 :['id':'3532']
Object2 :['id':'1456']
Object3 :['id':'1345']
}]
我正在尝试handlebars.js,我尝试了不同的模板选项,但没有一个起作用。
{{#Cards}}
{{#each this}}
object name: {{this}} Key: {{@key}} Value = {{this}}
{{/each}}
{{/Cards}}
如何在 html 中输出以下代码片段,以便它循环遍历整个 Cards 对象并显示类似的内容
<li>object name: object1: Key: id, value: 3532 </li>
<li>object name: object2: Key: id, value: 1456</li>
最佳答案
http://jsfiddle.net/CoryDanielson/r7unb/
从评论中,我认为您的数据结构如下:
var data = {
Cards: {
Object1: ['id','3532'],
Object2: ['id','1456'],
Object3: ['id','1345']
}
};
给定这组数据,您需要注册一个助手才能随意打印数组的项目。 (我在 Handlebars 文档中没有找到这样的方法)。该助手看起来像这样:
Handlebars.registerHelper('printIndex', function printIndex(index, arr) {
index = parseInt(index);
if ( index >= 0 && arr.length > index ) {
var r = arr[index];
} else {
throw new Error("printIndex helper: Array out of bounds. printIndex received " + index + ", array length is " + arr.length);
}
return r;
});
现在有了这个助手,您可以使用以下模板打印数据:
<ul>
{{#each Cards}}
<li>object name: {{@key}} Key: {{printIndex 0 this}} Value = {{printIndex 1 this}}</li>
{{/each}}
</ul>
关于javascript - Handlebars 循环穿过内部对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21950267/