2013-12-22 46 views
2

我已經在主幹中創建了一個View來呈現一個集合。它使用模板來格式化數據,模板HTML被寫入字符串變量。現在模板變得複雜了,我需要將它存儲在一個單獨的文件中。有沒有什麼方法可以從URL加載模板,在這種情況下什麼是最好的設計模式。以下是代碼:通過骨幹js中的URL加載模板

var PageView = Backbone.View.extend({ 
    template: _.template("<% _.each(items,function (item) { %><tr><td><%= item.page_id %></td><td><%= item.title %></td></tr><% }); %>"), 

    initialize: function() { 
     _.bindAll(this, 'render'); 
     this.model.bind('all', this.render); 
    }, 

    render: function() { 
     this.$el.html(this.template({ 
      items: this.model.toJSON() 
     })); 
    } 

}); 

有沒有像templateURL,以便它可以動態地從服務器上的其他文件中加載任何東西。

+1

這裏有http://stackoverflow.com/questions/8366733/external-template-in-underscore?lq=1類似的問題。可能是你在這裏得到你的解決方案。 – ram

+0

你考慮過使用requirejs嗎? – ekeren

回答

3

骨幹本身不提供一種方式來做到這一點,但也有許多不同的方式來做到這一點,並有大量的例子就如何建立必要的機制。

如果你選擇使用RequireJs(我建議你最終這樣做......考慮到你需要一些時間來學習它),你還需要RequireJS的文本插件。在backbone tutorials有一個使用RequireJS和骨幹項目中的文本插件的教程。

設置項目中的骨幹視圖加載外部模板之後是爲限定它們作爲視圖的依賴性和順便指出依賴性變量(projectListTemplate在下面的例子),爲簡單:

define([ 
    'jquery', 
    'underscore', 
    'backbone', 
    // Using the Require.js text! plugin, we load raw text 
    // which will be used as our views primary template 
    'text!templates/project/list.html' 
], function($, _, Backbone, projectListTemplate){ 
    var ProjectListView = Backbone.View.extend({ 
    el: $('#container'), 
    render: function(){ 
     // Using Underscore we can compile our template with data 
     var data = {}; 
     var compiledTemplate = _.template(projectListTemplate, data); 
     // Append our compiled template to this Views "el" 
     this.$el.append(compiledTemplate); 
    } 
    }); 
    // Our module now returns our view 
    return ProjectListView; 
}); 

另一種可能的方法是,如果您覺得不需要使用RequireJS,並且想要立即將模板移動到不同的文件,那麼可以使用簡單的自定義模板加載器。 Christophe Coenraets編寫了自己的文章,並將其用於一個示例性骨幹項目。他在github上提供了所有的源代碼,並提供了教程和解釋。

他在第一部分「外部化模板」中寫了關於他的method for externalizing templates

+0

我閱讀需要Js文檔,其邏輯性,但會使我的應用程序更復雜。第二個很簡單,適合我。謝謝 –

0

我會爲此使用require.js,它可能在開始時感覺像是過度殺傷,但最終它會爲大家帶來回報。

http://requirejs.org/

0

ReuireJS是一條很好的路線,但有點矯枉過正,並且增加了我們在上面使用requireJS插件的事實 - 我決定不使用它。 我的解決方案是JQuery的$加載查看之前不用彷徨的HTML模板,然後用結果加載視圖定義構造函數中的模板,然後以被稱爲options.template:

var template = $.get("/templates/needed_template.html") 
         .done(function (res) { 
          ns.myView = new MyView({template: res}); 
          ns.myView.render(); 
         }) 

在查看一面,我已經添加了這一點:

initialize: function() { 
    this.template = _.template(this.options.template);