Question

I am trying to implement a sprintf helper for Dust.js. For that, I would need to access the contents of the @sprintf block helper. The block may contain additional helpers or variables that need to be interpreted by the time I access the block body - meaning, I need to get the result of the body.

// JSON context: { name: "Fred" }
{@sprintf day="Saturday"}Hello {name}, today is %s!{/sprintf}

How can I access "Hello Fred, today is %s!" in my helper function?

Was it helpful?

Solution

I ended up using a code snippet from this gist. I modified it to suit my needs.

Here's my result (and answer to my own question):

dust.helpers.myHelper = function(chunk, context, bodies, params) {
  var output = "";
  chunk.tap(function (data) {
    output += data;
    return "";
  }).render(bodies.block, context).untap();
  console.log( output ); // This will now show the rendered result of the block
  return chunk;
}

This can also be abstracted to a separate function:

function renderBlock(block, chunk, context) {
  var output = "";
  chunk.tap(function (data) {
    output += data;
    return "";
  }).render(block, context).untap();
  return output;
}

dust.helpers.myHelper = function(chunk, context, bodies, params) {
  var output = renderBlock(bodies.block, chunk, context);
  console.log( output ); // This will now show the rendered result of the block
  return chunk;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top