When it comes to templates in JavaScript there are many options to fit a
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.
index.haml
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.
app.coffee
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.
1
| |
Then, we can load templates from the DOM using jQuery’s html()
function.
1
| |
If we have the following JavaScript object literal
1 2 3 | |
We can render HTML from it by calling Underscore’s _.template() method
and passing the html string stored in the variable template and also
the object literal company.
1
| |
The resulting HTML:
1 2 3 4 | |
Ajax
Usually we’d want to render HTML from multiple JavaScript objects. Suppose we make a request to our server and get the following JSON response:
1 2 3 4 5 | |
With CoffeeScript, We can process them in a single line
1
| |
Where, template is theme html string we grabbed from the DOM and
companies is an array of object literals - each representing a company
object c.
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.
The array htmlstr can then be added to a DOM node using jQuery’s
append() function:
1
| |
Here’s how the completed Ajax function looks like:
1 2 3 4 5 6 | |
And finally to compile the files just run
1
| |
Combined with HAML and CoffeeScript Comprehensions, Underscore’s
_template() function is a great way of rendering HTML from JSON data
for single page applications.
To learn more about CoffeeScript comprehensions read this. Feel free to fork the code of this article from this gist.