R.E.M. Web Development

Learning About Dust.js

Here's a zip of a working example, I but I couldn't get it to work exactly how I wanted to. Take a look at it, and if you can set the selected value in the drop down list, please let me know.



I stumbled into Dust.js and it seems like a great templating tool. So let the learning begin. One thing I really love about it so far is that there's a page you can go to to test your templates. What a great tool for learning!

This is the project home page:


But note that when I tried to use the template testing tool on this page, some of my templates were not working and I couldn't figure out why. So I posted my problem on stackoverflow and found out that I should be using this page to test my templates:



The best tutorial I've found thus far:



Here's a video tutorial:

A video introduction to Dust.js


This is the data model that I used to create my very first template:

"name": "SOME NAME",
"favorite_food": 1,
"food_options": [{id:1, value: "Ice Cream"},{id:2, value: "Pizza"},{id:3, value: "Fish"}]


And here's my first template, it's using the data model to output an h1 followed by a select box:

<option value="{id}">


To spice it up a bit, I added the @eq logic helper to set the selected option based on the value of the favorite_food property:

<option value="{id}"{@eq key=id value=favorite_food} selected="true"{/eq} >


Here's some code that shows how to actually use a template. In order to use Dust.js with Backbone.js (as an example), you need to create a function that takes your model object and renders the html for it.

In order to use Dust in your page:

<script src="https://raw.github.com/linkedin/dustjs/master/dist/dust-full-1.1.1.js" type="text/javascript" charset="utf-8"></script>


Here's a sample template that you can put in your html page:

<script type="text/x-template" id="building-list-item-template">
<li buildingId="{id}" class="building-list-item">
<div class="building-name">{name}</div>


To get a template function that you can pass your data into and get HTML back:

// compile the template
var buildingTemplate = dust.compile($("#building-list-item-template").html(),"tpl");

// load the compiled template into the dust template cache

// create a function that takes the data object
// in this case it's a 'building' object
var template = function(building) {
var result;
dust.render("buildingTemplate", building, function(err, res) {
result = res;
return result;


To use the template function:

//create a data object that the template will render
var building = {
id: 1,
name: "Empire State Building"

// append the template to it's host container