Monthly Archives: July 2013

How to use Underscore.js Templates in your Application

Recently I’ve posted about Mustache.js, a logic-less templating engine in JavaScript. Now, if you need advanced templates with logic, you can use Underscore.js. If you are using Backbone.js, you have it included anyways.

Here’s some test data I’ve made for generating HTML with the _.template() method from Underscore.js:

var collection = [
    {
        name: 'Patrick',
        age: 19,
        lastMatches: [
            {
                champion: 'Jax',
                hasWon: true
            },
            {
                champion: 'Vayne',
                hasWon: true
            }
        ]
    },
    {
        name: 'Kha',
        age: 18,
        lastMatches: [
            {
                champion: 'Ezreal',
                hasWon: false
            },
            {
                champion: 'Lee Sin',
                hasWon: true
            }
        ]
    },
    {
        name: 'Abu',
        age: 17,
        lastMatches: [
            {
                champion: 'Elise',
                hasWon: true
            },
            {
                champion: 'Shaco',
                hasWon: false
            }
        ]
    }
];

Now here is the corresponding Underscore template that you could include in a templates.html file.

<script type="text/template" class="template">
     <p> <%= name %> </p>
     <ul>
         <% _.each(lastMatches, function(match) { %>
             <% var color = (match.hasWon) ? 'green' : 'red'; %>
             <li class="<%= color %>"> <%= match.champion %> </li> 
         <% }); %>
     </ul>
</script>

By using these ERB-style delimiters <% %>, you can have JavaScript code in your template. Printing out a single variable is really easy:

<%= color %>

Finally, all we have to do is combining those pieces of code:

var compileHTML = _.template(jQuery("script.template").html())

_.each(collection, function(entity) {
   this.$el.append(compileHTML(entity)); 
});

See? Dead easy. Since we are using this template more than once, I’ve compiled it into the variable ‘compileHTML’. This speeds everything up. If you need to know something else, have a look at the documentation of Underscore.js.

Model, View and Router Extension/Inheritance in Backbone.js

Backbone.js supports inheritance of models, views and controllers. It’s pretty easy to understand and use, here is an example:

var Animal = Backbone.Model.extend({
    defaults: {
        name: 'Animal'
    },
    eat: function() {
        return this.get('name') + ' enjoys some food.';
    }
});

We started by declaring a class named ‘Animal’. It has one method and one attribute. Let’s extend it:

var Dog = Animal.extend({
    chaseCar: function() {
        return this.get('name') + ' is chasing a car.';
    }
});

By calling the Model.extend() method on our previously created class ‘Animal’, we can extend its functionality. In this example, we will create a ‘Dog’ model that inherits everything from ‘Animal’. We can test that by calling the Animal.eat() method on ‘Dog’:

var instance = new Dog({ name: 'Buddy' });
console.log(instance.eat());
console.log(instance.chaseCar());
Buddy enjoys some food.
Buddy is chasing a car.

If you are creating custom error models, this can be extremely useful. Inheritance is a common thing in other languages and I’m very happy to see it in JavaScript.