我正在使用骨干,我想在我的视图中解析我的第一个集合。
我的第一个问题是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>
答案 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 %>
<% }); %>
有几点需要考虑: