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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With