Skip to content

Instantly share code, notes, and snippets.

@zhannes
Created April 13, 2013 21:46
Show Gist options
  • Save zhannes/5380201 to your computer and use it in GitHub Desktop.
Save zhannes/5380201 to your computer and use it in GitHub Desktop.
Fetch a javascript template (html file) and then pass it data.
define(['jquery', 'handlebars'],function($,Handlebars){
/* use:
var tmpl = App.helpers.tmpl,
getCompiledTemplate = tmpl('foo', {});
getCompiledTemplate.then(function(content){
$('#something').html(content);
});
// or, verbose:
App.helpers.tmpl('foo', {}).then(function(html){
// do stuff with html
});
*/
// path relative to assets/templates/*
function loadTemplate(path){
var dfd = new $.Deferred;
// TODO - specify caching config
$.get('/templates/'+ path +'.html', function(data){
dfd.resolve(data);
});
return dfd.promise();
}
function compileTemplate(template,data){
// handlebars stuff
var tmpl = Handlebars.compile(template);
var html = tmpl(data);
return html;
}
function tmpl(path,data){
return loadTemplate(path).then(function(str){
var html = compileTemplate(str,data);
return html;
});
}
return {
tmpl: tmpl,
loadTemplate: loadTemplate,
compileTemplate: compileTemplate
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment