2012-03-23 121 views
5

我可以將我的模板放在單獨的.html文件中,只需在我的index.html中引用它們即可嗎?underscore.js和backbone.js的外部html模板

的index.html:

<script type="text/template" id="item-list" src="item-list-tmpl.html"></script> 

項目一覽tmpl.html:

<div><%= ItemDescription %><%= ItemCode %></div> 

我嘗試過,但問題是它並不顯示在index.html的,但它的模板上適當的點負載(認爲它是使用螢火蟲)

UPDATE

發現一個可能的解決方案,但是不推薦用於生產環境。

+0

看起來好像沒有簡單的解決方案。 [require.js](http://requirejs.org/)方法通常[出現爲解決方案](http://backbonetutorials.com/organizing-backbone-using-modules/),我從來沒有嘗試過,但它看起來像過多的工程設計。我希望有人帶來簡單直接的解決方案。 – fguillen 2012-03-23 09:20:01

+0

如果您有解決方案,即使對於您自己的問題,我認爲最好創建一個獨立答案,以便人們可以評論並投票。而且你也可以選擇它作爲正確的答案。 – fguillen 2012-03-23 10:58:18

回答

7

http://coenraets.org/blog/2012/01/backbone-js-lessons-learned-and-improved-sample-app/#comment-35324

得到這個這個創建一個單獨的js文件和你之前的js調用它的模型,收集和意見的文件。

tpl = { 

// Hash of preloaded templates for the app 
templates:{}, 

// Recursively pre-load all the templates for the app. 
// This implementation should be changed in a production environment. All the template files should be 
// concatenated in a single file. 
loadTemplates:function (names, callback) { 

    var that = this; 

    var loadTemplate = function (index) { 
     var name = names[index]; 
     //console.log('Loading template: ' + name); 
     $.get('templates/' + name + '.html', function (data) { 
      that.templates[name] = data; 
      index++; 
      if (index < names.length) { 
       loadTemplate(index); 
      } else { 
       callback(); 
      } 
     }); 
    } 

    loadTemplate(0); 
}, 

// Get template by name from hash of preloaded templates 
get:function (name) { 
    return this.templates[name]; 
} 

}; 

之後將其添加到您的路由器

tpl.loadTemplates(['filename-of-your-external-html-file'], function() { 
app = new AppRouter(); 
Backbone.history.start(); 
}); 

應該這樣做。但再次不推薦用於生產環境,因爲將有數百個用戶獲得請求,並可能會削弱您的應用程序。

+0

我可以根據需要在生產環境中加載模板,而不是一次加載所有模板? – 2013-06-11 17:03:12