2013-03-08 77 views
0

我通過調用API獲取了集合中的Json。Backbone.js - 在模板中獲取值

{ 
    "next_page_link": null, 
    "prev_page_link": null, 
    "posts": [ 
    { 
     "id": 1, 
     "public": true, 
     "actor": { 
     "displayName": "Srikanth Jeeva", 
     "id": "28" 
     } 
    }, 
    { 
    "id": 2, 
    "public": true, 
    "actor": { 
     "displayName": "Srikanth jeeva", 
     "id": "21" 
    } 
}] 
} 

這是瀏覽次數:

Raffler.Views.StreamsIndex = Backbone.View.extend({ 
    template: JST['streams/index'], 
    initialize: function(){ 
     this.collection.on('reset',this.render, this); 
    }, 

    render: function(){ 
     $(this.el).html(this.template({entries: this.collection})); 
     return this; 
    } 
}); 

現在我該怎樣得到模板這些條目?

<h1>Stream</h1> 
<%= entries["posts"] %> 

條目[「posts」]不顯示帖子?

回答

1

您應該循環使用數組,您可以使用<%>標籤在模板中使用JavaScript代碼。

一個例子可以是:

<ul> 
<% _.each(entries.posts,function(post){ %> 
    <li><%= post.actor.displayName %><li> 
<% }); %> 
</ul> 
+0

不知道爲什麼,它不顯示職位。但它顯示

2013-03-08 11:09:06

+0

將'this.collection'傳遞給模板不會做任何事情,因爲它是一個Backbone.Collection對象,並且您只需要這些屬性。你可以試着用'this.collection.toJSON()'來創建一個包含集合中每個模型屬性的對象,你可以閱讀更多[here](http://backbonejs.org/#Collection-toJSON) – Ingro 2013-03-08 11:19:35

+0

那也沒用。可能是Ajax調用僅在頁面加載完成後才能完成。 – 2013-03-08 11:33:56