迭代Handlebars中的对象数组不起作用

时间:2015-09-02 12:07:22

标签: javascript json handlebars.js

所以我试图迭代一个由服务器作为json对象返回的数组。我已经这样做了一次,它运行得很好,但这里的另一个似乎不起作用。

所以把手代码看起来像这样

  <script id="messageTemplate" type="text/x-handlebars-template">
{{#each response.data}}
<div class="message">
  {{#messages}}
  <h4>{{this.from}}</h4>
  <b>{{this.datetime}}</b>
  <p>{{this.body}}</p>
  {{/messages}}
</div>
{{/each}}
</script>

和我试图像这样迭代的json对象

 {
 "data": {
"id": 32607158,
"with_account": "user1",
"with_account_id": 8483786,
"last_message_preview": "XD",
"message_count": 289,
"messages": [{
  "id": 153359194,
  "from": "user1",
  "account_id": 20094939,
  "sender_id": 8483786,
  "body": "*hugs*",
  "conversation_id": 32607158,
  "datetime": 1439711004
}, {
  "id": 153359270,
  "from": "user2",
  "account_id": 20094939,
  "sender_id": 20094939,
  "body": "*hugs*",
  "conversation_id": 32607158,
  "datetime": 1439711023
}, {
  "id": 153359330,
  "from": "user1",
  "account_id": 20094939,
  "sender_id": 8483786,
  "body": "*hugs*",
  "conversation_id": 32607158,
  "datetime": 1439711044
}, {
  "id": 153359334,
  "from": "user2",
  "account_id": 20094939,
  "sender_id": 20094939,
  "body": "*hugs*",
  "conversation_id": 32607158,
  "datetime": 1439711048
}, {
  "id": 153359386,
  "from": "user1",
  "account_id": 20094939,
  "sender_id": 8483786,
  "body": "*hugs*",
  "conversation_id": 32607158,
  "datetime": 1439711057
}, {
  "id": 153359430,
  "from": "user2",
  "account_id": 20094939,
  "sender_id": 20094939,
  "body": "*hugs*",
  "conversation_id": 32607158,
  "datetime": 1439711065
}, {
  "id": 153359474,
  "from": "user1",
  "account_id": 20094939,
  "sender_id": 8483786,
  "body": "*hugs*",
  "conversation_id": 32607158,
  "datetime": 1439711078
}, {
  "id": 153359522,
  "from": "user2",
  "account_id": 20094939,
  "sender_id": 20094939,
  "body": "*hugs*",
  "conversation_id": 32607158,
  "datetime": 1439711090
}, {
  "id": 153359638,
  "from": "user2",
  "account_id": 20094939,
  "sender_id": 8483786,
  "body": "*hugs*",
  "conversation_id": 32607158,
  "datetime": 1439711106
}],
"done": false,
"page": 2,
"datetime": 1439711387
},
"success": true,
"status": 200
}

有人知道它为什么不起作用吗?提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您的each位置错误。 data是一个单独的对象,因此您无需迭代它。您可以对with

使用data语句
                {{#with response.data}}
                <div class="message">
                    {{#each messages}}
                    <h4>{{this.from}}</h4>
                    <b>{{this.datetime}}</b>
                    <p>{{this.body}}</p>
                    {{/each}}
                </div>
                {{/with}}

如果您使用响应对象编译模板,则with将变为

{{#with data}}