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

Lud*_*udo 1 mustache backbone.js underscore.js

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

我的第一个问题,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();
Run Code Online (Sandbox Code Playgroud)

这是我的渲染方法:

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

这是我的模板

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

mu *_*ort 14

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

this.template = _.template($('template'));
Run Code Online (Sandbox Code Playgroud)

应该这样:

this.template = _.template($('template').html());
Run Code Online (Sandbox Code Playgroud)

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

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

所以你想这样说:

this.$el.html(this.template({
    collection: this.collection.toJSON()
}));
Run Code Online (Sandbox Code Playgroud)

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

<% _.each(collection, function(model) { %>
  <%= model.name %>
<% }); %>
Run Code Online (Sandbox Code Playgroud)

有几点需要考虑:

  1. 骨干视图已经包含了jQuery this.el,this.$el所以没有必要$(this.el).
  2. 序列化数据通常使用传递给模板toJSON,这对Mustache和Handlebars来说是双倍的,因为他们不会理解任何其他内容.
  3. 你需要说<%= ... %>你的模板中有一些输出; <% ... %>简单地计算了一下的JavaScript代码,也不会留下任何痕迹,你必须使用插值分隔符(<%=以及%>用于在默认情况下).