2012-03-23 58 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