异步加载句柄模板 [英] loading handlebars template asynchronously

查看:95
本文介绍了异步加载句柄模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数使用ajax调用来获得模板并编译它以供使用,但我需要使用一个promise()函数,该函数会为我提供一个已编译的句柄模板(我将所有模板放在单独的文件中)所以我实际上可以使用它。

  function getTemplate(name){
$ .get('/'+ name + '.hbs')。success(function(src){
var template = Handlebars.compile(src);
//无法在这里返回模板
});



$ b $ p
$ b

如何通过承诺来做到这一点,所以我可以这样做: (函数(e){
getTemplate('form')。done(函数(e)){
$ b

  (模板){
$(body)。append(template({
name:My Name
})
);
});
});


解决方案

Chovy,我看到你接受了一个答案,但你可能有兴趣通过链接 .then()而不是来知道 getTemplate 可以。成功(),几乎写在问题中:

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

或者,采用charlietfl的想法来传递数据并返回完全的Promise组成片段:

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

nett效果与charlietfl的 getTemplate版本相同但是 .then()不需要显式创建Deferred。代码因此更加紧凑。


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"
           })
       );
    });
});

解决方案

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.

这篇关于异步加载句柄模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆