Emphasize nested models with the same context
source link: https://www.codesd.com/item/emphasize-nested-models-with-the-same-context.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Emphasize nested models with the same context
I want to use nested templates in underscoreJS, and access the same variables in the same way between parent and children templates.
//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 approach is to put the model in another object like stated 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})%>
Is there a cleaner/shorter solution ?
Solution, we can give the nested template the same context by passing obj
to it.
//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 %>
Looking into the annotated source for underscore, When no settings.variable
is given, the code results in the following at the top of every underscore template:
function anonymous(obj,_) {
var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
/* your template */
}
return __p;
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK