Underscore.js Templates With HAML and CoffeeScript

| Comments

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
_.templateSettings =  interpolate :/\{\{(.+?)\}\}/g

Then, we can load templates from the DOM using jQuery’s html() function.

1
template = $('#templates .company_li').html()

If we have the following JavaScript object literal

1
2
3
company = 
  ticker: 'AAPL'
  name: 'Apple Computers'

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
_.template( template, company)

The resulting HTML:

1
2
3
4
<li>
  <span class = 'ticker'>APPL</span>
  <span class="name">Apple Computers</span>
</li>

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
[{"id":1,"ticker":"AAPL","name":"Apple Inc"},
 {"id":2,"ticker":"ABC","name":"Amerisourcebergen Corp"},
 {"id":3,"ticker":"ABT","name":"Abbott Labs"},
 {"id":4,"ticker":"ACE","name":"Ace Ltd"},
 {"id":5,"ticker":"ADBE","name":"Adobe Sys Inc"}]

With CoffeeScript, We can process them in a single line

1
htmlstr = ( _.template( template, c) for c in companies)

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
$('#companies ul').append htmlstr.join ''

Here’s how the completed Ajax function looks like:

1
2
3
4
5
6
$.ajax 'companies',
  dataType: 'json',
  success: (companies) ->
    template = $('#templates .company_li').html()
    htmlstr = ( _.template( template, c) for c in companies)
    $('#companies ul').append htmlstr.join ''

And finally to compile the files just run

1
haml index.haml index.html && coffee -c app.coffee

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.

Comments