2011-09-27 110 views
6

我對骨幹js和小鬍子來說是相當新穎的。我正嘗試從rails json對象加載頁面加載骨幹集合(Object數組)以保存額外的調用。我有麻煩使用鬍子模板呈現骨幹收藏。問題使用小鬍子模板呈現骨幹集合

我的模型&合集

var Item = Backbone.Model.extend({ 

}); 

App.Collections.Items= Backbone.Collection.extend({ 
    model: Item, 
    url: '/items' 
}); 

,並查看

App.Views.Index = Backbone.View.extend({ 
    el : '#itemList', 
    initialize: function() { 
     this.render(); 
    }, 

    render: function() { 
     $(this.el).html(Mustache.to_html(JST.item_template(),this.collection)); 
     //var test = {name:"test",price:100}; 
     //$(this.el).html(Mustache.to_html(JST.item_template(),test)); 
    } 
}); 

在上面的視圖渲染,我也能夠使單一的模式(評價試驗obeject),而不是收藏。我完全在這裏受到衝擊,我試圖用下劃線模板&小鬍子,但沒有運氣。

這是模板

<li> 
<div> 
    <div style="float: left; width: 70px"> 
    <a href="#"> 
     <img class="thumbnail" src="http://placehold.it/60x60" alt=""> 
    </a> 
    </div> 
    <div style="float: right; width: 292px"> 
    <h4> {{name}} <span class="price">Rs {{price}}</span></h4> 
    </div> 
    </div> 
</li> 

和我對象數組那種看起來像這樣

enter image description here

+0

你可以發表你的鬍子模板? –

+0

@DerickBailey,添加了信息,請退房.. – RameshVel

回答

7

最後事實證明,鬍子不處理髮送到對象數組模板,所以我不得不用它來包裝這樣的其他物體

render: function() { 
    var item_wrapper = { 
      items : this.collection 
    } 

    $(this.el).html(Mustache.to_html(JST.item_template(),item_wrapper)); 

} 

和模板只是循環的項目陣列呈現HTML

{{#items}} 
<li> 
<div> 
    <div style="float: left; width: 70px"> 
    <a href="#"> 
     <img class="thumbnail" src="http://placehold.it/60x60" alt=""> 
    </a> 
    </div> 
    <div style="float: right; width: 292px"> 
    <h4> {{name}} <span class="price">Rs {{price}}</span></h4> 
    </div> 
    </div> 
</li> 
{{/items}} 

希望它可以幫助的人。

4

發生這種情況是因爲鬍鬚需要一個鍵/值對 - 屬於非空列表的數組值。從mustache man page,部分「非空列表」:

Template: 

{{#repo}} 
    <b>{{name}}</b> 
{{/repo}} 

Hash: 

{ 
    "repo": [ 
    { "name": "resque" }, 
    { "name": "hub" }, 
    { "name": "rip" }, 
    ] 
} 

Output: 

<b>resque</b> 
<b>hub</b> 
<b>rip</b> 

如果你只傳遞一個數組,鬍子沒有辦法知道在哪裏展開的模板中。

7

鬍子可以使用{{#.}}{{.}}{{/.}}

+1

這比接受的答案要好得多。請注意,如果您的數組是一個對象數組(請參閱OP問題),您可能希望執行類似於「{{#。}} {{name}} {{/。}}」的操作(請參閱OP問題) –

1

使用Hogan.js執行處理數組。

鑑於模板:

<ul> 
{{#produce}} 
    <li>{{.}}</li> 
{{/produce}} 
</ul> 

和背景:

var context = { produce: [ 'Apple', 'Banana', 'Orange' ]); 

我們得到:

<ul> 
    <li>Apple</li> 
    <li>Banana</li> 
    <li>Orange</li> 
</ul> 
+0

這也是一個有效的鬍鬚示例,Hogan是「針對小鬍子測試套件開發的」。 –