Tag Archives: UnderScore.js

Underscore.js Templates

After the post about why Underscore.js, I think it is best to follow up on one of the best parts of the library. Now, I haven’t had a chance to go through the new templating in jQuery, however what I have found with Underscore.js has allowed me to complete some very complicated tasks in my day to day work.

Lets take a look at the documentation for _.template and then we will dig into it a bit more:

template_.template(templateString, [context])
Compiles JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources. Template functions can both interpolate variables, using

<%= … %>, as well as execute arbitrary JavaScript code, with <% … %>. When you evaluate a template function, pass in a context object that has properties corresponding to the template’s free variables. If you’re writing a one-off, you can pass the context object as the second parameter to template in order to render immediately instead of returning a template function.


var compiled = _.template("hello: < %= name %>");
compiled({name : 'moe'});
=> "hello: moe"
var list = "< % _.each(people, function(name) { %>
<li>< %= name %></li>

< % }); %>";

_.template(list, {people : ['moe', 'curly', 'larry']});
=> "
<li>moe</li>
<li>curly</li>
<li>larry</li>
"

Pasted from <http://documentcloud.github.com/underscore/>

So what can we do with this? Lets take a look at showing some employee data:

Continue reading