Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

VGraupera commented Dec 21, 2012

Very useful, thanks

@jjok

This comment has been minimized.

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
You can’t perform that action at this time.