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%>