Platypus Header

Platypus Innovation Blog

6 May 2014

Javascript/html templating: underscore.js for the win

Man cutting steel with a template (cc) Washinton State Dept of Transport

After experimenting with Javascript templating libraries, we decided to use underscore.js. It scores over JQuery, Moustache and others in having a very clean and simple relationship between templating and normal code.

Underscore templates provide spaces where you can drop into javascript code - that's all they do, but it works better than trying to do more. Crucially, this gives you a lot of freedom - the full freedom of javascript.

For example, here is a simple loop using underscore:

<% for(var i=0; i<3; i++) print("

Line "

+i+"
"); %>
That middle section isn't the prettiest, but it's something every web developer should already understand -- and know how to write.

Compare this with the approach taken in JQuery templates:

{{each}}

Line $i

{{/each}}

This looks a little bit nicer -- but what are these new magic {{}} tags? Plus we need to pass in the list `[{i:1},{i:2},{i:3}]` in order to use it. And we have less ability to build richer more complex templates.

Hence, by taking a simpler code-based approach, underscore.js templates actually end up being more widely editable and more powerful.

About

The platypus caused consternation, shattered existing categories. It's existence was undeniable, but how should taxonomic theory be adapted to accommodate this uncomfortable fact? This blog is also hard to classify. It loosely follows the professional interests and activities of Daniel Winterstein. Topics are likely to range from business affairs to new media via data science and abstract mathematics.