0

好的人们,

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

有人遇到过这个问题吗?

4

2 回答 2

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; 

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

所以最好我会这样做:

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; 
于 2015-09-26T15:46:10.120 回答
0

转@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; 
});
于 2015-09-27T14:36:49.500 回答