Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

javascript - external html template for underscore.js and backbone.js

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...