【问题标题】:RequireJs text plugin and UnderscoreJs templatesRequireJs 文本插件和 UnderscoreJs 模板
【发布时间】:2015-09-25 15:54:10
【问题描述】:

好吧,

我正在使用 RequireJs 文本插件在我的主干应用程序中引入下划线模板 (.html)。不幸的是,我的模板中的下划线代码被呈现为纯文本。

define(['Backbone', 'text!Templates/BlogIndex.html', 'text!Templates/Elements/Blog/List.html'], function(Backbone, Template, ElementList){

var BlogPostIndexView = Backbone.View.extend({

    initialize: function () {
       this.template = _.template($(Template).html(), {posts : this.collection});
       this.render();

    },

    render: function (Template) {
        this.$el.html(this.template);
        return this;
    }

});

return BlogPostIndexView;

});

这是我的视图代码,你可以看到我正在拉入两个模板并设置它们。但是它被渲染为...

Globall Coach Blog Posts

<% _.each(posts, function(post){ %>
<%= _.escape(post.title) %>
<% }); %>

有人遇到过这个问题吗?

【问题讨论】:

  • text!... 没有给你文字,所以你只需要说_.template(Template)?从 Underscore 1.7.0 开始,_.template(tmpl, date) 不起作用,您现在需要 t = _.template(tmpl); h = t(data)。
  • 谢谢,看来我已经到了某个地方,伙计

标签: backbone.js requirejs underscore.js requirejs-text


【解决方案1】:

似乎您没有正确使用下划线模板功能。下划线将字符串编译成一个函数,您可以在其中输入数据。所以你的代码应该是这样的:

define(['Backbone', 'text!Templates/BlogIndex.html', 'text!Templates/Elements/Blog/List.html'], function(Backbone, Template, ElementList){

var BlogPostIndexView = Backbone.View.extend({

    initialize: function () {
       this.template = _.template($(Template).html())({posts : this.collection});
       this.render();

    },

    render: function () {
        this.$el.html(this.template);
        return this;
    }

});

return BlogPostIndexView; 

但我会进一步重构这一点,因为您通常希望使用最新数据动态重新渲染,因此我会将数据中的管道放入“渲染”方法中的模板而不是“初始化”。

所以我最好这样做:

define(['Backbone', 'text!Templates/BlogIndex.html', 'text!Templates/Elements/Blog/List.html'], function(Backbone, Template, ElementList){

var BlogPostIndexView = Backbone.View.extend({

    initialize: function () {
       this.template = _.template($(Template).html())
       this.render();

    },

    render: function () {
        this.$el.html(this.template({posts : this.collection}));
        return this;
    }

});

return BlogPostIndexView; 

【讨论】:

    【解决方案2】:

    转@mu-is-to-short 是正确的,requireJs 文本模块返回原始 html。

    这里是`define(['Backbone', 'text!Templates/BlogIndex.html', 'text!Templates/Elements/Blog/List.html'], function(Backbone, Template, ElementList){

    var BlogPostIndexView = Backbone.View.extend({
    
        initialize: function () {
           this.template = _.template(Template);
    
        },
    
        render: function (Template) {
            this.$el.html(this.template({posts : this.collection.toJSON()}));
            return this;
        }
    
    });
    
    return BlogPostIndexView; 
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 2015-01-28
      • 2015-11-15
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多