Using Dust.js with a client-side Backbone.js application
After playing around with dust.js I experimented with replacing iCanHaz with dust.js in my own projects. In the process I wrote a simple node script called Duster.js to make it easier to manage a directory of dust templates and automatically compile them when modified.
iCanHaz vs Dust.js
I am currently building a backbone.js application for the startup I work at and had been using Mustache with iCanHaz.js.
There were a couple things I didn't like about iCanHaz. The main thing was that managing multiple templates was messy and slow. I could either store them all in one big index.html file or load them via AJAX. I much prefer including precompiled .js templates that can be cached by the browser or served via CDN (similar to Google Closures templating system). There's no point in wasting resources building functions out of iCanHaz templates at runtime.
I was also impressed by the performance benchmarks of dust.js as well as the ability to pass unescaped HTML into templates (which is not possible in iCH).
Duster.js: an easier way to work with Dust.js with client-side apps
From reading the dust.js documentation there was no clear way to work with dust templates in a purely client-side browser-based approach (such as backbone.js). The docs seem to be targeted entirely at server-side NodeJS applications.
The only option for client side in the docs was to include the full dust library (a much larger file) and compile the templates on each browser load. Without precompiling the templates, dust.js would lose a lot of its benefits over other templating solutions (performance, browser caching, etc) so I wanted to find a way to a) auto compile templates when they are modified and b) have a working folder with a bunch of different templates.
So I wrote a simple Node script Duster.js to watch a directory of .dust templates and compile them into .js files which can be included into an HTML file.
Heres an example tweet template pulled from my backbone project:
Duster.js compiles this to tweet.js
Next, add compiled script to to index.html
Within the backbone app you'd call dust.render() note: this example is CoffeeScript:
Then calling Tweet.render().el.innerHTML will output:
Deploying to production
The only step left to deploy the project to production is to concatenate all of the various .js template files into one templates.js file. I personally use Jammit to do this.