tlovely
tlovely

Reputation: 715

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.

Upvotes: 0

Views: 552

Answers (2)

Vladimir Buskin
Vladimir Buskin

Reputation: 624

a bit late but https://jsfiddle.net/7jfzpgby/ to play

if (!dust.stringRender)
{
  dust.stringRender = function (template, data, cb)
  {
    var compiled = dust.compile(template);
    var template = dust.loadSource(compiled);
    dust.render(template, data, cb);
  };
}

dust.stringRender("Hello {name}, how are you?", { name: "Joe" }, function (error, output) {
  console.info(output);
})

Upvotes: 0

Interrobang
Interrobang

Reputation: 17434

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.

Upvotes: 2

Related Questions