Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 500
n0minal Avatar asked Mar 23 '12 05:03

n0minal


2 Answers

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.

like image 54
n0minal Avatar answered Sep 29 '22 06:09

n0minal


I wrote a solution for this, using jQuery and a simple TemplateCache object:

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

And I recently updated the template loading to use a jQuery plugin called TrafficCop: http://lostechies.com/derickbailey/2012/03/20/trafficcop-a-jquery-plugin-to-limit-ajax-requests-for-a-resource/

Hope that helps.

like image 36
Derick Bailey Avatar answered Sep 29 '22 08:09

Derick Bailey