是否有可能使dust.js模板同步? [英] Is it possible to render dust.js templates synchronously?

查看:171
本文介绍了是否有可能使dust.js模板同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个客户端HTML / JS模板系统使用引擎盖下dust.js的适配器。不幸的是,API预计渲染操作同步发生:渲染输出应该从渲染()调用返回。 Dust.js是异步的,通过渲染输出到一个回调函数。有没有什么办法来解决这个问题,无论是在灰尘API或通过一些疯狂的Javascript破解?

I am trying to write an adapter for a client-side HTML/JS templating system to use dust.js under the hood. Unfortunately the API expects render operations to occur synchronously: the rendered output should be returned from the render() call. Dust.js is asynchronous and passes render output to a callback function. Is there any way to work around this, either in the Dust APIs or through some crazy Javascript hack?

推荐答案

DustJS只会异步执行的东西时,它需要渲染的资源(模板,谐音)尚未全部被加载。

DustJS is only going to execute things asynchronously when the resources it needs to render (templates, partials) haven't already all been loaded.

如果一个模板的所有依赖您执行该模板,然后它会同步执行之前被加载(据我可以告诉无论如何)。所以,你可以这样做:

If all the dependencies of a template are loaded before you execute that template then it'll execute synchronously (as far as I can tell anyhow). So you can do something like:

var result;
dust.render("tpl", data, function(err, res) {
   result = res;
});
console.log(result); // result will actually already be filled out if dustjs didn't
// have to go look for resources somewhere.

下面是下面一个更全面的例子:
(这里是一个链接的jsfiddle这样你就可以运行它: http://jsfiddle.net/uzTrv/1/

Here is a fuller example below: (and here is a jsfiddle link so you can run it: http://jsfiddle.net/uzTrv/1/)

<script type="text/javascript" src="dust.js"></script>
<script>
    var tpl = dust.compile("Omg {#people} {.} {/people} are here! {>partial/}", "tpl");
    var partial = dust.compile("I'm a partial but I've already been included so things still run {how}", "partial");
    dust.loadSource(tpl);
    dust.loadSource(partial);

    var data = {
        people: ["jim", "jane", "jack", "julie"],
        how: "synchronously!"
    };

    var result;
    dust.render("tpl", data, function(err, res) { 
        result = res;
    });
    console.log(result);
</script>

有可能的情况下(除了我提到的),在那里我错了......我不知道dustjs一切。

There could be cases (besides the one I mentioned) where I'm wrong... I don't know everything about dustjs.

这篇关于是否有可能使dust.js模板同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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