underscore.js和backbone.js的外部html模板

时间:2012-03-23 05:52:21

标签: javascript backbone.js underscore.js

我可以将模板放在单独的.html文件中,只在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>

我尝试了但是问题是它没有在index.html上显示模板,但它加载到适当的位置(使用firebug查看)

更新

找到了可能的解决方案,但不建议用于生产环境。

2 个答案:

答案 0 :(得分: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();
});

应该这样做。但是再次不建议用于生产环境,因为会有数百个请求并且可能会使您的应用程序瘫痪。

答案 1 :(得分:1)

我为此编写了一个解决方案,使用jQuery和一个简单的TemplateCache对象:

http://lostechies.com/derickbailey/2012/02/09/asynchronously-load-html-templates-for-backbone-views/

我最近更新了模板加载以使用名为TrafficCop的jQuery插件:http://lostechies.com/derickbailey/2012/03/20/trafficcop-a-jquery-plugin-to-limit-ajax-requests-for-a-resource/

希望有所帮助。