2015-09-02 75 views
0

所以我試圖迭代由服務器返回的數組作爲json對象。我已經做了一次,它工作得很好,但這裏的另一個似乎並沒有工作。在Handlebars中無法正常工作的對象數組迭代

所以車把代碼看起來像這樣

<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 
} 

有誰知道爲什麼它不工作?提前感謝您的幫助。

回答

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}}