Dust.js is a JavaScript templating engine, barely maintained in the past years. Even the interactive tutorial in the official website is broken on Chromium browsers and has really strange behavior on Firefox. This reference sheet is a quick-to-look reference if you need to work in a project that still uses Dust.
To reference a variable, use curly brackets.
<div>This is the value of a variable: {myVariable}.</div>
<div>You can use dot-notation to access object's attributes: {myObject.attribute}</div>
Create a section using {#section}{/section}
. Sections are used to change the context of the references, helping with verbose dot-notation. If a property isn't found in the current context, Dust will look at upper-level contexts to find the data.
{
commonAttr: 'parent',
parentAttr: 'only parent',
child: {
commonAttr: 'child',
}
}
This will display 'parent': {commonAttr}.
{#child}
This will display 'child': {commonAttr}.
Child doesn't have this attribute, but parent have as 'only parent': {parentAttr}.
{/child}
Create a special section starting with ?
to check if a variable exists / its truthiness. Use $
instead to check if a variable doesn't exist / falsiness. The only false values for Dust are null
, undefined
, and an empty Array ([]
).
{?variable} This will show only if variable is TRUE. {/variable}
{$variable} This will show only if variable is FALSE. {/variable}
If you include {:else}
inside a conditional section, everything after that will be displayed if the condition is false, like a else
clause on an if
statement.
{?thisVariableIsFalse} This won't be displayed. {:else} But this will. {/thisVariableIsFalse}
To loop through the elements of an array, create a section using the array as reference.
If the array has simple elements (i.e. number
, string
, boolean
), use {.}
to reference it inside the loop section.
{ myArray: [10, 20, 30] }
{#myArray} <span>{.}</span> {/myArray}
<span>10</span>
<span>20</span>
<span>30</span>
If the array has objects as its elements, just use the name of the attributes to reference them.
{ myArray: [{myNumber: 10}, {myNumber: 20}, {myNumber: 30}] }
{#myArray} <span>{myNumber}</span> {/myArray}
<span>10</span>
<span>20</span>
<span>30</span>
Use ${idx}
to get the index of the current item in a loop section.
Use ${len}
to get the length of the array in a loop section.