Skip to content

Instantly share code, notes, and snippets.

@BenJam
Last active December 10, 2015 22:38
Show Gist options
  • Save BenJam/4504134 to your computer and use it in GitHub Desktop.
Save BenJam/4504134 to your computer and use it in GitHub Desktop.
A util function to load external templates into a backbone project.
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('tpl/' + 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];
}
};
var templates = [
'template1',
'template2',
'template3'
];
tpl.loadTemplates(templates, function(){
app = new AppRouter();
Backbone.history.start();
});
@BenJam
Copy link
Author

BenJam commented Jan 10, 2013

This usage is for the document ready within the router but i imagine one could use tpl.loadTemplate('template', function(){return}); in a Backbone.View's initialisation. Might be a slight performance hit on page change for larger template files though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment