Your browser doesn't support the features required by impress.js, so you are presented with a simplified version of this presentation.

For the best experience please use the latest Chrome, Safari or Firefox browser.


Dust.js templates

Prof. Cesare Pautasso
http://www.pautasso.info
[email protected]
@pautasso

Dust.js

{value}

json

{ name: "Peggy"
, address: { street: "via Buffi"
           , number: 13 }
}

dust

{name}<br/>
{address.street} {address.number}

HTML

Peggy<br/>
via Buffi 13

Replace the JSON element with its value

{#array}

json

{ names: [ "a", "b", "c" ] 
}

dust

{#names}
 {.}
{/names}

HTML

a b c

Iterate over all elements of the names array
Use once if names is not an array
Skip if names does not exist in the model

{#array}

json

{ users: [ {name: "a"}
         , {name: "b"}
         , {name: "c"} ] 
}

dust

{#users}
 {$idx}. {name}
{:else}
 no users found
{/users}

HTML

1. a
2. b
3. c

Control what happens if the array is empty with {:else}

Predefined counters: $idx, $len

Conditional Section

json

{ name: "Peggy"
, address: { street: "via Buffi"
           , number: 13 }
}

dust

{^telephone}
 {! telephone missing !}
{/telephone}
{?address}
 {! address present !}
{/address}

Decide whether to include parts of the template depending on whether elements are found (?) or missing (^) in the model

{>partial /}

Reuse templates by including them within other templates

dust

{>"template_name" /}
{>"template_{name}" /}

The choice of which template to include can be dynamic, based on a value found in the model

Parameters

Pass parameters to sections and partials

dust

{#section param="value"}

String constant parameter

{>"template_name" param=value /}

Parameter value taken from model named value

Where to render?

Rendering on the client

dust.loadSource(
  dust.compile('template code', "template_name")
);

Compile on the client and load the template once

<script src="/views/template_name.js"></script>

Precompile on the server and load the template on the client

dust.render("template_name", 
            { /* model json to be rendered */ }, 
 function(err, out) {
  if (!err) {
    //show the result of the model rendering
    view.innerHTML = out;
  }
});

Asynchronously render the model using the template whenever the view needs refreshing

References

Use a spacebar or arrow keys to navigate