javascript - Handlebars 循环穿过内部对象

标签 javascript ember.js handlebars.js

我有一个看起来像这样的对象:

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/

相关文章:

javascript - Sequelize中如何进行算术运算?

javascript - 如何使用 firefox addon sdk 将脚本即 gmail.js api directlty 注入(inject) gmail 内容?

ember.js - Ember init 无法识别 _super

javascript - emberjs 为一个路由使用多个路径/url

javascript - 嵌套的 HandlebarsJS #each helpers 与 EmberJS 不工作

javascript - response.success 给我 "Object #<Object> has no method ' success'"错误

ember.js - 尝试注册未知工厂: `controller:application`

javascript - 无法从 Handlebars 模板访问 metalsmith-collections 'path' key ?

javascript - 模型中的函数接收消息 ** 不是函数 **