Subscribe via RSS Feed

Templates In Backbone.js

June 2, 2014 5 Comments

One of the more important components of Backbone.js is templates. Templates are essentially pieces of markup that can be use to create a bunch of different reusable copies of that same markup. 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. Backbone.js uses the template engine of Underscore.js which makes sense because Backbone has a hard dependency on Underscore.Backbone allows for different multiple template engine.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.

   window.EventView = Backbone.View.extend({
      template: _.template($('#calendar-event-template').html()),
      render: function() {
        $(this.el).html(this.template(this.model.toJSON()));
        return this;
      }
    });

As we can see in the above code snippet, we have used underscore template. The _.template() Underscore method takes as its argument the “html” extracted from the type=”text/template” tag. The result of the _.template() call is a function that will return a string with the things inside replaced with key-values passed into the function. Since the template only requires that title and description values be defined .in case we have the local variables, we can invoke the function as event_html({title: title, description: description}). To append that to the existing table cell we should convert the resulting HTML string into a jQuery object and append it to the cell element.
In the above code snippet we have created an individual view that corresponds to single calendar event. The results are much simpler conceptually. All that I need implement in the view class is a template attribute and a render method. As we can see the render method just extracts the attributes from the model and passes them to the template function.
Now we have used underscore template(), the most popular one. But many of us could question this method. So, let us venture through an complete code step by step to try to understand this technique better.
Let us make a simple code for saving some data of a student and afterwards retrieving them. To make this a success we have to take help of a model and a view. Let the worry for _.template() later.

var Student = Backbone.Model.extend({
    defaults: {
        name: 'student name',
        age: student age,
        class:10
    }
});
var StudentView = Backbone.View.extend({
   tagName: 'li',
   initialize: function(){
     this.render();
   },
   render: function(){
     this.$el.html( this.model.get('name')  ' ('   this.model.get('age')  ') - '   this.model.get('class'));
  }
});

Now as we can see above there is a near perfect set of simple codes. But if we try to introduce different models or views. The code itself will start to look complex. Because there is one line which will get us into trouble.

this.$el.html( this.model.get('name')  ' ('   this.model.get('age')  ') - '   this.model.get('class'));

For a limited entity this line could work fine. But as large the data becomes, so as this line of code. Now let us use the template method and see what happens.

var Student = Backbone.Model.extend({
    defaults: {
        name: 'student name',
        age: student age,
        class:10
    }
});
var StudentView = Backbone.View.extend({
    tagName: 'li',
    my_template: _.template(" () - "),
    initialize: function(){
        this.render();
    },
    render: function(){
        this.$el.html( this.my_template(this.model.toJSON()));
    }
});

There is definitely some difference in the above code. Because we have use template method in this. A new line have been introduced.

my_template: _.template(" () - "),

In the above line we have defined a template using underscore js. It will compile the template and in time of passing the data, it will return the html view as per the code.
Our template has been defined now we are ready to show the data in html. But before that we can surely see that the code has been altered in this line from the previous.

this.$el.html( this.my_template(this.model.toJSON()));

We called the template and we need to pass the data to that template. We will have access to the model object . We know that toJSON() method just pass the object parameters. So,we will have the parameter passed from the model Student and show it via html.
The Underscore template engine is a fine solution for Backbone applications. However, when it comes to syntax template, some people prefer other options. Apart from the default Underscore template system, one of the more popular template engines used with Backbone.js applications is the Handlebars template 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="student-template" type="text/x-handlebars-template">
 <table>
  <thead>
    <tr>
      <th>Student Name</th>
      <th>Age</th>
      <th>Class</th>
    </tr>
  </thead>
  <tbody>
      {{#each []}}
      <tr>
          <td>{{this.studentname}}</td>
          <td>{{this.age}}</td>
          <td>{{this.class}}</td>
      </tr>
      {{/each}}
  </tbody>
</table>
</script>
 </script>
 <script type="text/javascript">
 var Student = Backbone.Model.extend({
     defaults:{
        name: 'New Student',
        birthday: 'February 19, 1998',
        age:16,
        class:10,
    },
     initialize: function() {
        console.log('New student created...');
    }
 });
 var junior = new Student({ id: 1, name: ‘James’, birthday: 'May 21, 1998',age:16,class:10 });
var senior= new Student({ id: 2, name:’Jones’, birthday: 'January 6, 1998', age:16,class:10 });
var Student = Backbone.Collection.extend({
    model: Student,
    initialize: function() {
        console.log('New collection initialized...');
    }
});  
 var studentArray = [Junior,Senior];
var student = new Student(studentArray);  
var StudentView = Backbone.View.extend({
    el: '.content',
    initialize:function(){
        this.render();
    },
    render: function () {
        var source = $('#student-template').html();
        var template = Handlebars.compile(source);
        var html = template(student.toJSON());
        this.$el.html(html);
    }
});
 var studentView = new StudentView();
 </script>
</body>
</html> 

As you can see we’ve added many things than before. We have used a model ‘student’ and instantiated two others by the name of ‘Junior’ and ‘Senior’.

var Student = Backbone.Model.extend({
     defaults:{
        name: 'New Student',
        birthday: 'February 19, 1998',
        age:16,
        class:10,
    },
     initialize: function() {
        console.log('New student created...');
    }
 });
 var junior = new Student({ id: 1, name: ‘James’, birthday: 'May 21, 1998',age:16,class:10 });
var senior= new Student({ id: 2, name:’Jones’, birthday: 'January 6, 1998', age:16,class:10 });

Collection and adding those models to the collection:

var studentArray = [Junior,Senior];
var student = new Student(studentArray);  

We have also loaded up Handlebars and utilized it in the view’s render function. There are many other template engines out there to choose from.

<script src="js/handlebars.js" type="text/javascript"></script> 
var template = Handlebars.compile(source);

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

Some related articles :

1>Introduction to Backbone.js

2>Models in Backbone.js

3>Underscore Methods in Backbone.js

4>Backbone Routes and History

5>Collections in Backbone.js

6>Understanding view in Backbone.js

7>WHY SHOULD WE USE SERVER SIDE IN BACKBONE.JS?

8>Backbone.js at a glance

If you find this article helpful, you can connect us in Google+ and Twitter.

Sign Up to read the rest of the content

Email will be used only for updates of our site

No Thanks

Filed in: Backbone.js