【问题标题】:Underscore nested templating with same context下划线嵌套模板具有相同的上下文
【发布时间】:2014-03-26 09:42:54
【问题描述】:

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

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

【问题讨论】:

    标签: javascript templates backbone.js underscore.js underscore.js-templating


    【解决方案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;
    }
    

    【讨论】:

    • 我也在为此苦苦挣扎,直到我在 Chrome 中调试时注意到生成的模板函数,然后通过查看下划线的注释源来确认它。
    【解决方案2】:

    我发现这种方法很好:

    //Backbone Render
    this.$el.html(this.template.call(this.model.attributes, this.model.attributes));
    
    //Underscore template
    <%=backgroundColor%>
    <%=subTemplate.call(this, this)%>
    
    //Subtemplate
    <%=backgroundColor%>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多