2011-09-27 197 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是“针对小胡子测试套件开发的”。 –