jquery - loading handlebars template asynchronously -
i'm trying write function give me compiled handlebars template (i have templates in separate files) using ajax call template , compile use, need use promise can use it.
function gettemplate(name){ $.get('/'+name+'.hbs').success(function(src){ var template = handlebars.compile(src); //can't return template here. }); } how do promises can like:
$("a").click(function(e){ gettemplate('form').done(function(template){ $("body").append(template({ name: "my name" }) ); }); });
chovy, see have accepted answer might interested know gettemplate can, chaining .then() rather .success(), written in question :
function gettemplate(name) { return $.get('/'+name+'.hbs').then(function(src) { return handlebars.compile(src); }); } or, adopting charlietfl's idea pass in data , return promise of composed fragment :
function gettemplate(name, data) { return $.get('/'+name+'.hbs').then(function(src) { return handlebars.compile(src)(data); }); } the nett effect identical charlietfl's version of gettemplate .then() makes unnecessary create deferred explicitly. code more compact.
Comments
Post a Comment