0

我想在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})%> 

是否有一个更清洁/更短的解决方案吗?

回答

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; 
} 
+0

我也为此而努力,直到我发现生成的模板功能,同时在Chrome中进行调试,然后通过查看下划线的注释源来确认它。 –

0

我发现这种方法,这是很好:

//Backbone Render 
this.$el.html(this.template.call(this.model.attributes, this.model.attributes)); 

//Underscore template 
<%=backgroundColor%> 
<%=subTemplate.call(this, this)%> 

//Subtemplate 
<%=backgroundColor%>