我想在underscoreJS中使用嵌套模板,并以相同的方式在父模板和子模板之间访问相同的变量。
//Backbone :
this.model = new Backbone.model.extend({backgroundColor:red});
this.$el.html(this.template(this.model.attributes);
//Underscore template:
<%=backgroundColor%>
<%=subTemplate()%>
//Underscore subtemplate:
<%=backgroundColor%>
JAshkenas方法是将模型放在另一个对象中,如陈述here
//Backbone :
this.$el.html({model : this.model.attributes});
//But that means accessing "model" for every property, and having to pass "model" to each subtemplate
<%=model.backgroundColor%>
<%=subTemplate({model:model})%>
是否有更清洁/更短的解决方案?
答案 0 :(得分:1)
解决方案,我们可以通过将obj
传递给嵌套模板来为嵌套模板提供相同的上下文。
//Backbone:
this.model = new Backbone.model.extend({backgroundColor:red});
this.$el.html(this.template(this.model.attributes);
//Underscore template:
<%= backgroundColor %>
<%= subTemplate(obj) %>
//Underscore subtemplate:
<%= backgroundColor %>
查看annotated source for underscore,当没有给出settings.variable
时,代码会在每个下划线模板的顶部生成以下内容:
function anonymous(obj,_) {
var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
/* your template */
}
return __p;
}
答案 1 :(得分:0)
我发现这种方法很不错:
//Backbone Render
this.$el.html(this.template.call(this.model.attributes, this.model.attributes));
//Underscore template
<%=backgroundColor%>
<%=subTemplate.call(this, this)%>
//Subtemplate
<%=backgroundColor%>