Created
March 11, 2012 11:20
-
-
Save neuronix/2016071 to your computer and use it in GitHub Desktop.
Rendering dynamic parameters in a dust.js helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
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
Very useful, thanks