variety of needs. A very simple and lightweight option is the small
_.template() function in the Underscore.js library.
In this posts I’ll show you how to use it with HAML and CoffeeScript.
First we’ll need to add the underscore library to our HAML file and a some code that will serve as our template. I usually add templates inside a hidden div.
We do the heavy lifting using CoffeeScript.
By default Underscore uses ERB like delimiters. Since I prefer Mustache style, I set up Underscore to use double curly braces as delimiters.
Then, we can load templates from the DOM using jQuery’s
1 2 3
We can render HTML from it by calling Underscore’s
and passing the html string stored in the variable
template and also
the object literal
The resulting HTML:
1 2 3 4
1 2 3 4 5
With CoffeeScript, We can process them in a single line
template is theme html string we grabbed from the DOM and
companies is an array of object literals - each representing a company
The previous is a CoffeeScript comprehension, which iterates over each
company. In every iteration a company gets rendered into a HTML string
which is stored internally in an array by the CoffeeScript compiler. All
of this is done inside an auto-executable function which returns the
internal array and assigns it to the variable
htmlstr can then be added to a DOM node using jQuery’s
Here’s how the completed Ajax function looks like:
1 2 3 4 5 6
And finally to compile the files just run
Combined with HAML and CoffeeScript Comprehensions, Underscore’s
_template() function is a great way of rendering HTML from JSON data
for single page applications.