Using Templates in Backbone.js

One of the more important components of Backbone.js is using templates. What are templates? Templates are essentially pieces of markup that you can use to create a bunch of different reusable copies of that markup (including all the styles and hierarchy that you want) but populating each component with different data. Used in combination with views, they are great for doing such as iterating over a collection of models to display a list of data for some purpose. You’ll see how it all fits together in what follows.

By default, Backbone.js uses the templating engine of Underscore.js which makes sense because Backbone has a hard dependency on Underscore. However, if you’re not a big fan of the way that Underscore does templating or you just want to use another templating engine, Backbone allows for that as well. The possibilities are limitless. But let’s first take a look at an Underscore.js template because that will work out of the box with Backbone.js. You do not need to load up anything else to use templates.

To get started, let’s define a model and instantiate a few models…

var Artist = Backbone.Model.extend({
    defaults: {
        name: 'New Artist',
        birthday: 'January 1, 1970',
        hometown: 'Los Angeles, CA',
        favoriteColor: 'blue',
    }
});

var biggie = new Artist({ id: 1, name: 'Notorious BIG', birthday: 'May 21, 1972', hometown: 'Brooklyn, NY', favoriteColor: 'green' });
var mike = new Artist({ id: 2, name: 'Mike Jones', birthday: 'January 6, 1981', hometown: 'Houston, TX', favoriteColor: 'blue' });
var taylor = new Artist({ id: 3, name: 'Taylor Swift', birthday: 'December 13, 1989', hometown: 'Reading, PA', favoriteColor: 'red' });

Next let’s define a collection and let’s add those models to the collection…

var Artists = Backbone.Collection.extend({
    model: Artist
});

var artistArray = [biggie, mike, taylor];
var artists = new Artists(artistArray);  

Note: If you are not familiar with models and collections, it will definitely be worth your while to read the sections on Backbone.js Models, Backbone.js Collections. And if you haven’t yet, you may as well read the entry on Backbone.js Views while you’re at as this will also be helpful in understanding this section.

Now that we have our collection of models in it, did you know that we can loop the collection over it using templates? Well, as it turns out, we can! How do we do this? Let’s create a template…

<script type="text/template" id="artist-list-template">
<table>
  <thead>
    <tr>
      <th>Name</th>
	  <th>Hometown</th>
	  <th>Favorite Color</th>
    </tr>
  </thead>
  <tbody>
    <% _.each(artists, function(artist) { %>
      <tr>
        <td><%= artist.get('name') %></td>
        <td><%= artist.get('hometown') %></td>
        <td><%= artist.get('favoriteColor') %></td>
      </tr>
    <% }); %>
  </tbody>
</table>
</script>

That’s pretty neat. Underscore uses the <% %> tags (known as bee sting syntax) to specify templates. The <%= %> specification with the equals sign means we want to evaluate and render the value out to the browser window. If we need to escape HTML in our value we can use <%- %> instead. The tags without these definitions are used for things life if-else conditions and loops. Here we can see we are looping over all of the items in our collection and using the get method for each model to get the data we’re looking for.

Now we can actually pass this into Underscore’s template function. We use the “models” property for a Backbone.js collection to access each model in the Collection as an array…

var template = _.template($('#artist-list-template').html(), {artists: artists.models});
$(".content").html(template);

The rendered content will be injected into a div with the “content” class.

Most of the time when you’re developing a Backbone application, you’re going to be using a view in Backbone.js to do the rendering…

var ArtistListView = Backbone.View.extend({
    el: '.content',
    
    initialize:function(){
        this.render();
    },
    render: function () {
        var template = _.template($('#artist-list-template').html(), {artists: artists.models});
        this.$el.html(template);
    }
});
var artistListView = new ArtistListView();

Handlebars

The Underscore templating engine is a fine solution for your Backbone applications. However, when it comes to templating syntaxes, some people prefer other options. Apart from the default Underscore templating system, one of the more popular templating engines used with Backbone.js applications is the Handlebars templating engine. Handlebars uses the popular mustache style syntax which involves the use of {{ brackets }} to indicate dynamic values.

So the following implementation shows the same thing that we did above, only this time we’re loading up Handlebars and using it to render the dynamic content for our application…

<!DOCTYPE html>
<html>
<head>
<title>Backbone Application</title>
<script src="js/jquery.js" type="text/javascript"></script> 
<script src="js/underscore.js" type="text/javascript"></script> 
<script src="js/backbone.js" type="text/javascript"></script> 
<script src="js/handlebars.js" type="text/javascript"></script> 
</head>
<body>
 
<div class="content"></div>

<script id="artist-list-template" type="text/x-handlebars-template">

<table>
  <thead>
    <tr>
      <th>Name</th>
	  <th>Hometown</th>
	  <th>Favorite Color</th>
    </tr>
  </thead>
  <tbody>
      {{#each []}}
	  <tr>
	      <td>{{this.name}}</td>
	      <td>{{this.hometown}}</td>
	      <td>{{this.favoriteColor}}</td>
	  </tr>
	  {{/each}}
  </tbody>
</table>
</script>

</script>
 
 
<script type="text/javascript">

var Artist = Backbone.Model.extend({

    defaults:{
        name: 'New Artist',
        birthday: 'January 1, 1970',
        hometown: 'Los Angeles, CA',
        favoriteColor: 'blue',
    },

    initialize: function() {
        console.log('New artist created...');
    }

});

var biggie = new Artist({ id: 1, name: 'Notorious BIG', birthday: 'May 21, 1972', hometown: 'Brooklyn, NY', favoriteColor: 'green' });
var mike = new Artist({ id: 2, name: 'Mike Jones', birthday: 'January 6, 1981', hometown: 'Houston, TX', favoriteColor: 'blue' });
var taylor = new Artist({ id: 3, name: 'Taylor Swift', birthday: 'December 13, 1989', hometown: 'Reading, PA', favoriteColor: 'red' });

var Artists = Backbone.Collection.extend({

    model: Artist,

    initialize: function() {
        console.log('New collection initialized...');
    }
});  

var artistArray = [biggie, mike, taylor];
var artists = new Artists(artistArray);  


var ArtistListView = Backbone.View.extend({
    el: '.content',

    initialize:function(){
        this.render();
    },
    render: function () {
        var source = $('#artist-list-template').html();
        var template = Handlebars.compile(source);
        var html = template(artists.toJSON());
        this.$el.html(html);
    }
});

var artistListView = new ArtistListView();

</script>
</body>
</html> 

As you can see we’ve loaded up Handlebars and the utilized it in the view’s render function. In my humble personal opinion the template looks a lot cleaner in this second version. There are many other templating engines out there to choose from, you’ll just have to pick the one that’s right for you.

Thus concludes our brief introduction into what templating is and how you can use it in Backbone.js. There are many templating tools and libraries out there that you can use to make your Backbone applications more efficient, clean, reusable, and scalable.

, , , 9bit Studios E-Books

Like this post? How about a share?

Stay Updated with the 9bit Studios Newsletter

5 Responses to Using Templates in Backbone.js

  1. DL says:

    I have faund min mistake

    artist.get(‘favoriteColor’)__)__

    superfluous ‘)’

  2. Eduardo says:

    Hi, I have found this article very useful. Let me ask you a question, what should I do if I want to fetch data from rest api with the same structure like “Artist” model and then display that items in an loop.
    Thank you very much.

    • Ian says:

      Hey there Eduardo — It kinda depends on the language and technology that your API is written in but presumably you’d get some sort of JSON object back from the API that you could iterate through. So if you were using PHP, your API would be returning a JSON encoded associative array of artists. I actually wrote an article called RESTful Backbone.js Implementation using Slim API that kind of shows the process of getting/sending data to/from an API with Backbone.js and PHP, but the process would be similar for other languages.

      • Eduardo says:

        Thank you very much Ian! I am actually getting the JSON data via Slim api. That article will be really great for me!

Leave a Reply

Your email address will not be published. Required fields are marked *