RequireJs文本插件和UnderscoreJs模板

时间:2015-09-25 15:54:11

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

好人,

我正在使用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) %>
<% }); %>

有没有人遇到过这个问题?

2 个答案:

答案 0 :(得分:0)

好像你没有正确使用下划线模板功能。下划线将字符串编译成一个可以管道输入数据的函数。所以你的代码应该是这样的:

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; 

但是我会进一步重构这个,因为你通常想用最新的数据动态地重新渲染,所以我会把数据中的管道放在“render”方法的模板中,而不是“初始化”。

所以我最好这样做:

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; 

答案 1 :(得分:0)

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

这里是`定义([&#39; Backbone&#39;,&#39; text!Templates / BlogIndex.html&#39;,&#39; text!Templates / Elements / Blog / List.html&#39 ;],函数(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; 
});
相关问题