underscore.js 和backbone.js 的外部 html 模板 [英] external html template for underscore.js and backbone.js
问题描述
我可以将我的模板放在单独的 .html 文件中,然后在我的 index.html 中引用它们吗?
index.html :
项目列表-tmpl.html :
<%= ItemDescription %><%= ItemCode %>
我试过了,但问题是它没有在 index.html 上显示模板,但它加载到了正确的位置(使用 firebug 查看)
更新
找到了可能的解决方案,但不推荐用于生产环境.
从 http://coenraets.org/blog/2012/01/backbone-js-lessons-learned-and-improved-sample-app/#comment-35324
为此创建一个单独的 js 文件,并在模型、集合和视图的 js 文件之前调用它.
tpl = {//应用程序预加载模板的哈希值模板:{}、//递归地预加载应用程序的所有模板.//这个实现应该在生产环境中改变.所有的模板文件都应该是//连接在一个文件中.loadTemplates:函数(名称,回调){var that = this;var loadTemplate = 函数(索引){var name = 名称[索引];//console.log('加载模板:' + 名称);$.get('templates/' + name + '.html', function (data) {that.templates[name] = 数据;指数++;如果(索引<名称.长度){加载模板(索引);} 别的 {打回来();}});}加载模板(0);},//从预加载模板的散列中按名称获取模板获取:函数(名称){返回 this.templates[name];}};
然后将此添加到您的路由器
tpl.loadTemplates(['filename-of-your-external-html-file'], function () {app = new AppRouter();Backbone.history.start();});
应该可以.但同样不推荐用于生产环境,因为会有数百个请求并可能导致您的应用程序瘫痪.
Can i put my template on a separate .html files and just reference them in my index.html?
index.html :
<script type="text/template" id="item-list" src="item-list-tmpl.html"></script>
item-list-tmpl.html :
<div><%= ItemDescription %><%= ItemCode %></div>
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)
UPDATE
Found a possible solution but is not recommended for production environment.
Got this from http://coenraets.org/blog/2012/01/backbone-js-lessons-learned-and-improved-sample-app/#comment-35324
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];
}
};
After that add this to your router
tpl.loadTemplates(['filename-of-your-external-html-file'], function () {
app = new AppRouter();
Backbone.history.start();
});
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屋!