是否可以在模板中传递cid字段?

Eri*_*rik 2 model-view-controller template-engine backbone.js underscore.js underscore.js-templating

我有一个视图,其模板如下所示:

<script type="text/template" id="template">
   <div id="<%=cid=>"></div>
   <label><%= label %></label>
   <input type="text" id="search_input" />
   <input type="button" id="search_button" value="Search" />
</script>
Run Code Online (Sandbox Code Playgroud)

我需要使用模型数据渲染此模板,因此我执行以下操作:

render: function () {
   var template = _.template( $("#template").html(), this.model.toJSON());
   this.$el.html( template );
   return this;
}
Run Code Online (Sandbox Code Playgroud)

但不幸的是this.model.toJSON()没有将cid(clientId)传递给我的模板.你可以解释一下如何在我的模板中访问cid,你如何处理这个问题?

Kir*_*ril 7

toJSON只是克隆attributes数组.这就是没有cid的原因.如果你需要模型中的cid,你可以将它混合在模板对象中:

var templateData = _.extend(this.model.toJSON(), { cid: this.model.cid });
var template = _.template( $("#template").html(), templateData);
Run Code Online (Sandbox Code Playgroud)

但如果您需要一个唯一的ID div- 我建议使用_.uniqueId()