Skip to content

Instantly share code, notes, and snippets.

@neuronix
Created March 11, 2012 11:20
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neuronix/2016071 to your computer and use it in GitHub Desktop.
Save neuronix/2016071 to your computer and use it in GitHub Desktop.
Rendering dynamic parameters in a dust.js helper
// Handy function to render dynamic parameters in a dust.js helper
function renderParameter(name, chunk, context, bodies, params) {
if (params && params[name]) {
if (typeof params[name] === "function") {
var output = "";
chunk.tap(function (data) {
output += data;
return "";
}).render(params[name], context).untap();
return output;
} else {
return params[name];
}
}
return "";
}
// Example
// Template
<div>
{@MyHelper single="{id}" comp="{type}_{id}" text="example" /}
</div>
// Data
{type: "myType", id: "42"}
// Helper
dust.helpers["MyHelper"] = function (chunk, context, bodies, params) {
var single = renderParameter("single", chunk, context, bodies, params); // single = "42"
var comp = renderParameter("comp", chunk, context, bodies, params); // single = "myType_42"
var text = renderParameter("text", chunk, context, bodies, params); // text = "example" -> this is not necessary, access params.text directly
<...your code here>
return chunk;
}
@VGraupera
Copy link

Very useful, thanks

@jjok
Copy link

jjok commented Mar 22, 2017

A much simpler way resolve a variable is:

var single = context.resolve(params.single);

From http://stackoverflow.com/questions/32465011/how-to-pass-a-variable-into-a-dust-helper-function-key

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment