如何使用Node.js + express在Handlebar中的数组内循环数组

时间:2013-08-16 12:47:37

标签: node.js handlebars.js

我有JSON数组如下:

{outer:[
    {
      Key1:"ID001", 
      Key2:[
             {
               innerKey1:"Myval1",
               innerKey2:"Myvalue2"
             }
            ]
    }
]}

现在在我的HTML文件中:

<div>
    {{#each outer}}
        <b>key1:</b> {{this.Key1}} <br/>
        {{#each this.Key2}}
           <b>InnerKey1:</b> {{this.innerKey1}} <br/>
        {{/each}}
    {{/each}}
</div>

但它没有表现出任何内在价值。任何人都可以帮助如何循环内部数组对象(即上面的Key2)。我需要为此编写一个单独的帮助器吗?

1 个答案:

答案 0 :(得分:7)

您必须在对象或数组交互之间进行选择:

{
  outer:[{
    Key1:"ID001", 
    Key2:{
      innerKey1:"Myvalue1",
      innerKey2:"Myvalue2"
    },
    Key3:[
      "Myvalue4",
      "Myvalue5"
    ]    
  }]
}

<div>
  {{#each outer}}
    key1: {{this.Key1}} <br/>
    {{#each this.Key2}}
      {{@key}}: {{this}}
    {{/each}} <br/>
    {{#each this.Key3}}
      {{@index}}: {{this}}
    {{/each}}
  {{/each}}
</div> 

输出:

key1: ID001 
innerKey1: Myvalue1 innerKey2: Myvalue2 
0: Myvalue4 1: Myvalue5

http://codepen.io/rafaelcastrocouto/pen/qgrFE