简体   繁体   中英

Underscore nested templating with 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;
}

I found this approach which is nice :

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

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

//Subtemplate
<%=backgroundColor%>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM