javascript - 问题使用 Mustache 模板渲染 Backbone 集合

标签 javascript jquery templates backbone.js mustache

我对 backbone js 和 Mustache 很陌生。我试图在从 rails json 对象加载页面时加载 Backbone 集合(对象数组)以保存额外的调用。我在使用 mustache 模板渲染 Backbone 集合时遇到问题。

我的模型和收藏是

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

在上面的 View 渲染中,我可以渲染单个模型(注释测试对象),但不能渲染集合。我在这里完全被打动了,我尝试了下划线模板和 mustache ,但没有运气。

这是模板

<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

最佳答案

最后证明 mustache 不处理发送到模板的对象数组,所以我不得不像这样用其他对象包装它

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

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

}

并且在模板中只是循环 items 数组来呈现 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}}

希望对大家有帮助。

关于javascript - 问题使用 Mustache 模板渲染 Backbone 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7570811/

相关文章:

c++ - 在编译时将函数指针转换为 std::uintptr_t

c++ - 模板 <unsigned int N> 是什么意思?

javascript - 如何在此代码中从 "on click"更改为鼠标悬停时

javascript - NetSuite上的ClientScript如何知道一条记录处于哪种模式?

jquery - 在 Google map 信息窗口中使用 jQuery

javascript - Jquery 列生成器插件 : 40 times faster in Windows Firefox. 为什么?

c++ - 带有嵌套模板类的 C2143

javascript - 未收到来自 Express 服务器的 GET 响应

javascript - 获取数组中最长字符串的长度

jquery - 更改事件 <li> Bootstrap CSS