-
Notifications
You must be signed in to change notification settings - Fork 70
Helpers
This page provides a listing of the helpers provided by dustjs-helpers
.
These comparison helpers take two inputs, key
and value
. key
is the "left-hand" comparison.
If the test passes, the contents of the helper are output.
Note that all of these helpers support an {:else}
block so you can output an alternative result if the test is false.
{! "CS201" == courseName !}
{@eq key="CS201" value=courseName}
You are enrolled in CS201
{:else}
You are not enrolled in CS201
{/eq}
{! passingGrade > grade !}
{@gt key=passingGrade value=grade}
You didn't pass! Try again.
{/gt}
Unless a type is specified, both key
and value
will be compared using their current types. This is especially important for comparisons involving {@eq}
. If you need to coerce to a certain type, use the type
parameter.
{! WRONG: Looks for a key named `false` in the context !}
{@eq key=passwordCorrect value=false}Wrong password{/eq}
{! WRONG: Compares passwordCorrect to the string "false" !}
{@eq key=passwordCorrect value="false"}Wrong password{/eq}
{! RIGHT: Coerces !}
{@eq key=passwordCorrect value="false" type="boolean"}Wrong password{/eq}
{@select}
provides a key value that can be tested within its scope to output desired values. It mimics the switch/case statement.
Any of the previous comparison helpers can be used inside {@select}
.
{@select key="{foo}"}
{@eq value="bar"}foobar{/eq}
{@eq value="baz"}foobaz{/eq}
{@default}default output{/default}
{/select}
{@select key=temperature}
{@lte value=0}It's freezing cold!{/lte}
{@gt value=35}It's really hot!{/gt}
{@default}It's just right!{/default}
{/select}
Each test condition is executed in order. If a condition is true, its body is output and all subsequent condtions are skipped. If no test condition has been met and a @default is encountered, it will be executed and the select process terminates.
The math helper provides simple computational capabilities. Operations supported are:
- add
- subtract
- multiply
- divide
- mod
- abs
- floor
- ceil
The general syntax is:
{@math key="operand1" method="mathOpName" operand="operand2" /}
The helper computes a result using the key, method, and operand values.
{@math key="16" method="add" operand="4"/} - Result will be 20
{@math key="16.5" method="floor"/} - Result will be 16
{@math key="16.5" method="ceil"/} - Result will be 17
{@math key="-8" method="abs"/} - Result will be 8
{@math key="{$idx}" method="mod" operand="2"/} - Return 0 or 1 according to $idx value
Sometimes you need to choose something to output based on the result of a math helper computation. For example, if the table row number is odd, you want to give it a gray background.
{#rows}
<tr class="
{@math key=$idx method="mod" operand=2}
{@eq value=0}
even
{:else}
odd
{/eq}
{/math}
">
{/rows}
The above evaluates the mod with the given key and operand, i.e. $idx % 2
and then checks if the output
is 0, and prints the block inside the @eq helper, if not the else block. Be careful to use numeric values for tests and not strings, e.g. {eq value="0"} will never be true.
Another example
{@math key="13" method="add" operand="12"}
{@gt value=123}
13 + 12 > 123
{/gt}
{@default}
Math is fun
{/default}
{/math}
Using the nested @eq @lt etc. syntax allows you to output values like a select/case similar to the select helper.
WARNING: Planned deprecation in 1.6.0
There are a few cases where a simple true/false or exists/non-exists or single eq or lt or gt test won't suffice. For those, there is the if helper.
Some examples
{@if cond="{x} < {y} && {b} == {c} && '{e}'.length || '{f}'.length"}
<div> x is less than y and b == c and either e or f exists in the output </div>
{/if}
{@if cond="({x} < {y}) || ({x} < 3)"} <div> x<y or x<3 {/if}
{@if cond="{x} < {y} && {b} == {c} && '{e}'.length || '{f}'.length "}
<div> x is less than y and b == c and either e or f exists in the output </div>
{:else}
<div> x is >= y </div>
{/if}
Caveat #1: In the above example, if there is a possibility of undefined or false value for the {x} or {y} in the JSON, the correct syntax would be to check it exists and then check for {x} > {y}. This is a known limitation since, {x} returns nothing when the value of x is undefined or false and thus results in invalid js condition in the if helper
{@if cond="'{x}'.length && '{y}.length && {x} < {y} && {b} == {c} && '{e}'.length > 0 || '{f}'.length > 0 "}
<div> x is less than y and b == c and either e or f exists in the output </div>
{/if}
Caveat #2: The if helper internally uses javascript eval, for complex expression evaluation. Excessive usage of if may lead to sub-optimal performance with rendering, since eval is known to be slow.
When outputting lists of things, you often need to do something different for the last iteration. Consider the case
My friends are:
{#friends}
{name},
{/friends}
As written this will produce Hurley,Kate,Sawyer,Desmond,
leading to the "dangling comma problem".
This can be fixed by using the {@sep}
helper tag as follows:
My friends are:
{#friends}
{name}{@sep},{/sep}
{/friends}
The {@sep}
helper tag will output its body content unless this is the final iteration of the containing loop.
WARNING: Planned deprecation in 1.6.0
The idx helper tag provides a way to get the index of the current iteration. The need for this has been eliminated by the introduction of {$idx}
.
For example,
My friends are:
{#friends}
<option value="id_{@idx}{.}{/idx}">{name}</option>
{/friends}
Here we are using idx to generate a unique id for each option tag in a dropdown. Therefore, we would have "id_0, id_1,... for id values. Within the idx helper {.} references the current iteration count.
The {@size}
helper computes the size of the key
parameter. The size computed depends on the type of the subject parameter as follows:
- Array - number of elements, [1,2,3,4] has size=4
- String - length of the string, "abcdef" has size=6
- Object - Number of properties in the object, {a:4, b:8, c:15, d:16} has size=4
- Number - Value of the number, 23 has size 23 and 3.14 has size 3.14
- Undefined, 0, empty string - zero
- Any other value - length after conversion to string
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.
Remove this tag when done debugging.
{! current context, write to output !}
{@contextDump/}
{! full context, write to console !}
{@contextDump key="full" to="console" /}
{! specific key !}
{@contextDump key="{foo.bar}" /}