Skip to content

Instantly share code, notes, and snippets.

@saaji
Created December 12, 2011 19:33
Show Gist options
  • Save saaji/1468716 to your computer and use it in GitHub Desktop.
Save saaji/1468716 to your computer and use it in GitHub Desktop.
Tiny JavaScript Template loader/compiler with Handlebars.
var JST = {
prefix: 'js/templates/',
extension: '.hbs',
compile_template: function(name, data) {
this[name] = Handlebars.compile(data);
},
register_partial: function(name, data) {
this[name] = Handlebars.registerHelper(name, Handlebars.compile(data));
},
load_templates: function(list) {
_.each(list, function(name){
$.ajax({
url: this.prefix + name + this.extension,
success: function(data) { this.compile_template(name, data) },
dataType: 'text',
context: JST,
async: false
});
}, JST);
},
load_partials: function(list) {
_.each(list, function(name){
$.ajax({
url: this.prefix + '_' + name + this.extension,
success: function(data) { this.register_partial(name, data) },
dataType: 'text',
context: JST,
async: false
});
}, JST);
}
};
// Usage Example
//
// JST.load_partials(['header', 'footer']);
// JST.load_templates(['main']);
//
// $("#main").html(JST["main"]({ some: "data" }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment