Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to render dust.js templates synchronously?

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?

like image 294
cliff.meyers Avatar asked Mar 24 '12 03:03

cliff.meyers


1 Answers

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.

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>

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

like image 181
Matt Wonlaw Avatar answered Sep 26 '22 02:09

Matt Wonlaw