2015-09-25 60 views
0

好的人,RequireJs文本插件和模板UnderscoreJs

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

有沒有人有過這個問題?

+1

不'發短信!...'給你的文字,讓你只需要說'_.template(模板)'?和'_.template(TMPL,日期)'不工作從Underscore 1.7.0開始,你需要't = _.template(tmpl); h = t(data)'now。 –

+0

謝謝你看起來像我現在正在某個地方呆過 –

回答

0

打開@ MU-是對短是正確的,requireJs文本模塊返回原始的HTML。

這`定義([ '骨幹', '文字!模板/ BlogIndex.html', '文字!模板/元/博客/ List.html'],功能(骨幹,模板,元素列表){

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; 
}); 
0

好像你沒有正確使用下劃線模板函數。 Underscore將字符串編譯爲一個可以在其中傳輸數據的函數。所以你的代碼應該是這樣的:

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;