Using Helpers

Dust helpers extend the templating language in the same way as context helpers. Unlike context helpers, however, Dust helpers are global and can be used in any template without including them in the context.

Helpers look like {@helper}.

Installing Helpers

Officially supported helpers are bundled separately in the dustjs-helpers library. After the dustjs-linkedin library is loaded, follow the same instructions in the Setup guide to install dustjs-helpers.

If you are using Node.js, then you can require the helpers directly and get back a Dust instance with the helpers preloaded:

var dust = require('dustjs-helpers');

Logic Helpers

The helpers library comes with the following logic helpers:

These helpers allow you to print content if one value compared in a certain way to another value is true. For each helper, you specify the first value with the key attribute and the second value with the value attribute. Both key and value can point to a reference or a literal value. Wrap literal values in quotes and leave references un-quoted.

In the following example, the first helper looks for the value of level in the underlying JSON data and checks if it is equal to the literal string “master”. The second checks to see if the value for the age reference is greater than the value of the starfighterRentalAge reference.

{@eq key=level value="master"}You are no longer a Padawan. {/eq} {@gt key=age value=starfighterRentalAge}Rent a Starfighter!{/gt} { "level": "master", "age": 27, "starfighterRentalAge": 25 }

Else

For all logic helpers, you can create an {:else} block that will render if the test is false.

{@eq key=level value="master"} You are no longer a Padawan. {:else} You have much to learn, young Padawan. {/eq} { "level": "padawan" }

Casting

If you are comparing a literal value to one that you know is not a string (e.g. a number or a boolean), make sure to specify the type attribute so Dust knows how to cast the literal value.

{@eq key=bilbosAge value="50" type="number"}Looking nifty at fifty, Bilbo! {/eq} {@gt key=gandalfsAge value="10000"}Gandalf is really old...{/gt} { "bilbosAge": 50, "gandalfsAge": 12345 }

Separator Helper

Iterating over lists sometimes requires slightly different treatment of the first or last items in the list. The {@sep} helper and its companions {@first} and {@last} provide this functionality.

{#guests} {@first}Hello {/first} {@last}and {/last} {.}{@sep}, {/sep} {@last}!{/last} {/guests} { "guests": ["Alice", "Bob", "Charlie"] }

Select Helper

The @select helper can be nested around the other logic helpers to form a switch-like structure, allowing you to take one action based on multiple comparisons with a single key value. You move the key attribute into the @select helper and set only a value attribute for each logic helper inside the @select.

You can specify what to do if none of the conditions are true using a @none helper in the @select. Its opposite, the @any helper, is run if any of the conditions are true, in addition to those true conditions.

When a true logic helper condition is found in the @select, Dust executes the condition’s body and skips the rest of the truth tests. {@any} and {@none} tests are always evaluated, no matter where they occur.

<span class=" {@select key=testEnabled} {@any}test-enabled {/any} {@none}test-disabled {/none} {@eq value="puppies"}test-puppies{/eq} {@eq value="bunnies"}test-bunnies{/eq} {/select} "> { "testEnabled": "bunnies" }

Note that the @default helper has been deprecated as of Dust Helpers version 1.6.0. This helper was similar to @none, except there could only be one instance per @select, and it needed to be placed after all logic helpers to ensure that all previous comparisons were false.

Math Helper

The {@math} helper can perform simple math operations in a template and then either output or truth-test the result. It accepts key and method parameters as well as an operand parameter for operations that require two values, like adding or subtracting.

You can nest logic helpers inside a math helper to test the result of the operation.

<ul> {#flavors} <li {@math key=$idx method="mod" operand="2"} {@eq value="0" type="number"} class="alt"{/eq} {/math}> {name} </li>{~n} {/flavors} </ul> { "flavors": [ { "name": "red bean" }, { "name": "green tea" }, { "name": "mango" }, { "name": "peanut" } ] }

Printing the Result

To simply output the result of the mathematical expression, use the {@math} helper without a body.

There is {@math key=100 method="subtract" operand=progress/}% left to do. { "progress": 70 }

Allowed Operations

The {@math} helper supports these operations as the method:

Debugging with @contextDump

The {@contextDump} helper outputs the current context portion of the JSON data model to the output stream. This can help with debugging if you suspect the context data is not as expected or you aren’t sure what the current context is.

You can set key="full" to print the full context, and to="console" to print to the console.

Remove this helper when you are done debugging.

{#houses.gryffindor} {! Default: key="current" and to="output" !} {@contextDump/} {! Check your console for the full context !} {@contextDump key="full" to="console"/} {/houses.gryffindor} { "houses": { "gryffindor": { "founder": "Godric Gryffindor" }, "hufflepuff": { "founder": "Helga Hufflepuff" } } }

Adding New Helpers

Helpers are written in the same way as context helpers. Once you’ve written your helper, attach it to the dust.helpers object.

function yell(chunk, context, bodies, params) {
  return chunk.tap(function(data) {
    return data.toUpperCase();
  }).render(bodies.block, context).untap();
}
dust.helpers.yell = yell;

Returning a Value (Dust 2.7.2)

Helpers can return a value directly and act like a reference or a section. When a helper has no body, it acts like a reference. You can pass filters to the reference-like helper by adding a filters attribute.

{@myHelper value=name filters="|s|uc" /}

If a helper has a body, it acts more like a section. Dust will iterate over the value that is returned from the helper.

{@myHelper value=name}Hello {foo}!{/myHelper}

If you need more control over the default behavior (for example, if you want to render a named body or not HTML-sanitize by default), your helper needs to return the Chunk that was passed to it.

Returning a Chunk

Write and render to the chunk directly, then return it from your helper. Dust will inject the Chunk as-is into the template without applying any filters. If you want your helper to respect filters, you can call dust.filter manually.

Remember that chunk.write does not HTML-escape data passed to it, so be careful what you are writing.


Fork me on GitHub