Search code examples
javascriptnode.jsdust.js

Is there a way to render a string dust template without compiling it first?


Is it possible to do something like this with dustjs? As oppose to compiling a template, then referring to it in the render method.

>    
> var dust = require('dustjs-linkedin');
>
> dust.stringRender("Hello {name}, how are you?", { name: "Joe" }, function(err, res) {
>   console.log(res);
> });
'Hello Joe, how are you?'
>

I know that stringRender is a fictitious method; its just for clarity.


Solution

  • You could do this yourself with just a couple lines of code-- this is Javascript, after all.

     function stringRender(source, context, callback) {
        var tmpl = dust.loadSource(dust.compile(source));
        return dust.render(tmpl, context, callback);
     }
    

    However, we recognize this is a typical case and so you can use dust.renderSource exactly as you used your function stringRender above. (The code above is basically the code of dust.renderSource.)

    dust.renderSource("Hello {name}!", { name: "Jim" }, function(err, data) {
      ...
    });
    

    Or as a stream:

    dust.renderSource("Hello {name}!", { name: "Jim" }).pipe(...)
    

    However, you should not use this in production because compilation is the slowest part of the Dust template lifecycle. In production, you should always precompile and cache your templates.