如何在模板视图中解析主干集合

时间:2013-01-29 00:51:55

标签: backbone.js underscore.js mustache

我正在使用骨干,我想在我的视图中解析我的第一个集合。

我的第一个问题是undescore真的是最好的方法吗?我听说过mustache.js

接下来的事情是,我不知道该怎么办:

var A = new Model();
var B = new Model();
var Mole = new Collection([A, B]);
var View = View({model: A, collection: Mole });
View.render();

这是我的渲染方法:

render: function(){
  this.template = _.template($('template').html());
  $(this.el).html(this.template(this.collection.models)); //I don't know what to send here
}

这是我的模板

<script type="text/template" id="template">
  <% _.each(collection, function(model){ %> //I don't know what to get here
    <% model.name %>
  <% }); %>
</script>

1 个答案:

答案 0 :(得分:14)

首先,_.template需要模板中的文本,而不是jQuery对象。这意味着:

this.template = _.template($('template'));

应该是这样的:

this.template = _.template($('template').html());

然后编译的模板函数将要查看数据的键/值对;来自fine manual(这适用于Mustache,Handlebars和Underscore BTW):

  

评估模板函数时,传入一个数据对象,该对象具有与模板的自由变量对应的属性。

所以你想这样说:

this.$el.html(this.template({
    collection: this.collection.toJSON()
}));

然后你可以在你的模板中说出这个:

<% _.each(collection, function(model) { %>
  <%= model.name %>
<% }); %>

有几点需要考虑:

  1. 骨干视图已在this.$el中包含this.el jQuery,因此无需$(this.el)
  2. 序列化数据通常使用toJSON传递给模板,这对Mustache和Handlebars来说是双倍的,因为他们不会理解任何其他内容。
  3. 您需要说<%= ... %>才能在模板中获得一些输出; <% ... %>只是评估一些JavaScript代码,它不会留下任何东西,你必须使用插值分隔符(默认为<%=%>)。