Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loading handlebars template asynchronously

I'm trying to write a function that will give me a compiled handlebars template (I have all my templates in separate files) using an ajax call to get the template and compile it for use, but I need to use a promise so I can actually use it.

function getTemplate(name){
    $.get('/'+name+'.hbs').success(function(src){
       var template = Handlebars.compile(src);
       //can't return the template here.
    });
}

How do I do this with promises so I can do something like:

$("a").click(function(e){
    getTemplate('form').done(function(template){
       $("body").append(template({
               name: "My Name"
           })
       );
    });
});
like image 563
chovy Avatar asked Apr 20 '13 09:04

chovy


1 Answers

Chovy, I see you have accepted an answer but you might be interested to know that getTemplate can, by chaining .then() rather than .success(), be written almost as in the question :

function getTemplate(name) {
    return $.get('/'+name+'.hbs').then(function(src) {
       return Handlebars.compile(src);
    });
}

or, adopting charlietfl's idea to pass in data and return a Promise of a fully composed fragment :

function getTemplate(name, data) {
    return $.get('/'+name+'.hbs').then(function(src) {
       return Handlebars.compile(src)(data);
    });
}

The nett effect is identical to charlietfl's version of getTemplate but .then() makes it unnecessary to create a Deferred explicitly. The code is thus more compact.

like image 184
Beetroot-Beetroot Avatar answered Nov 05 '22 17:11

Beetroot-Beetroot