对于underscore.js和Backbone.js的外部HTML模板 [英] external html template for underscore.js and backbone.js
问题描述
我可以把一个单独的.html文件我的模板,只是引用它们在我的index.html?
Can i put my template on a separate .html files and just reference them in my index.html?
index.html的:
index.html :
<script type="text/template" id="item-list" src="item-list-tmpl.html"></script>
项列表,tmpl.html:
item-list-tmpl.html :
<div><%= ItemDescription %><%= ItemCode %></div>
我尝试过,但问题是,它不显示在index.html的模板,但它加载在适当位置(使用Firebug查看吧)
I tried it but the problem is it doesn't show the template on index.html but it loads on the proper spot (viewed it using firebug)
找到一个可行的解决方案,但不建议在生产环境中。
Found a possible solution but is not recommended for production environment.
推荐答案
从<一个得到这个href=\"http://coenraets.org/blog/2012/01/backbone-js-lessons-learned-and-improved-sample-app/#comment-35324\">http://coenraets.org/blog/2012/01/backbone-js-lessons-learned-and-improved-sample-app/#comment-35324
此创建一个单独的js文件和你的js之前调用它的模型,收集和意见的文件。
Create a separate js file for this and call it before your js files for model,collection and views.
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();
});
这应该这样做。但同样不推荐用于生产环境,将有数百get请求,并可能削弱你的应用程序。
That should do it. But again not recommended for production environment as there will be hundreds to get request and may cripple your application.
这篇关于对于underscore.js和Backbone.js的外部HTML模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!