How to use templates in backbone js - Learning Backbone js
This entry is part 6 of 14 in the series for A Complete Guide for Learning Backbone Js
- Introduction and Installation
- Representing your data in javascript
- Defining Models in backbone js
- Adding Validations in models backbone js
- Explaining views in backbone js
- How to use templates in backbone js
- How to improve templates in backbone js
- Collections in backbone js
- Collection views in backbone js
- Template helpers in backbone js
- How to use namespace in backbone js
- How to handle dom events in backbone js and define your custom events (Live Demo)
- Routing in backbone js
Agenda
In the previous lessons we learned how to define views and display data, but problem was complex views. In this lesson, we will learn how to use templates in backbone js.
What we have till now
So from the previous lesson, we have this PersonView:
var Person = Backbone.Model.extend({
defaults: {
name: 'Guest User',
age: 23,
occupation: 'worker'
}
});
var PersonView = 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('occupation') );
}
});
// calls from console
// var person = new Person;
// var personView = new PersonView({ model: person });
//$(document.body).html(personView.el); // this is not ideal but good enough for demo.
What was the problem
The problem is this code is:
this.$el.html( this.model.get('name') + ' (' + this.model.get('age') + ') - ' + this.model.get('occupation') );
This will go more complicated if we have images or some complex views etc.
Using a template
Let’s use a template, and we pass data to that template, and in return, that template returns the full HTML view. Take a look at this code and let’s discuss it line by line.
var Person = Backbone.Model.extend({
defaults: {
name: 'Guest Worker',
age: 23,
occupation: 'worker'
}
});
var PersonView = Backbone.View.extend({
tagName: 'li',
my_template: _.template("<strong><%= name %></strong> (<%= age %>) - <%= occupation %>"),
initialize: function(){
this.render();
},
render: function(){
this.$el.html( this.my_template(this.model.toJSON()));
}
});
// calls from console
// var person = new Person;
// var personView = new PersonView({ model: person });
//$(document.body).html(personView.el); // this is not ideal but good enough for demo.
So we introduced a new line i.e.,
my_template: _.template("<strong><%= name %></strong> (<%= age %>) - <%= occupation %>"),
Backbone js has a feature that you can define a template using underscore js that we included in lesson 1, and it will compile the template, and then when ever you pass the data, it will return the HTML view as per the code. So in the above line, we defined a template using
_.template("<strong><%= name %></strong> (<%= age %>) - <%= occupation %>")
and we assigned it to
my_template = .......
Now backbone js will compile it and define a function behind the scenes. Next modification that we did was:
this.$el.html( this.my_template(this.model.toJSON()));
// it was
//this.$el.html( this.model.get('name') + ' (' + this.model.get('age') + ') - ' + this.model.get('occupation') );
We called the template and we need to pass the data to that template. We will have access to the model object as we will call:
// calls from console
// var person = new Person;
// var personView = new PersonView({ model: person });
So personView has access to the model, and previously we have seen that toJSON() method just pass the object parameters. Cool. Now let’s see the code again and discuss the full flow:
var Person = Backbone.Model.extend({
defaults: {
name: 'Guest Worker',
age: 23,
occupation: 'worker'
}
});
var PersonView = Backbone.View.extend({
tagName: 'li',
my_template: _.template("<strong><%= name %></strong> (<%= age %>) - <%= occupation %>"),
initialize: function(){
this.render();
},
render: function(){
this.$el.html( this.my_template(this.model.toJSON()));
}
});
Fire up the console and fire these commands
var person = new Person; // a person object created...
var personView = new PersonView({ model: person });
personView.el // ---->; You can call this method and it will display the view..
$(document.body).html(personView.el); // --->; This will add output to the dom. This is not ideal but good enough for demo.
Whats going on?
- A personView object is created.
- Model person has been passed to that personView object.
- So personView has access to the person object.
- personView constructor will call render method.
- render method will call template via my_template and pass data to my_template
- my_template will accepts the parameters and assign proper values and return to render.
Cool :)
Output on Chrome Console
Now Lets see what chrome developer tools say:
The templates we will be defined is known as inline templates. We can improve this code too. Let’s see that in the next lesson.
Source code
If you are facing any issues. Check out the source code files at github. I will be creating more and more directories in the same repo regarding each post. Still, if you have any doubts you can comment on the blog post itself, and I will try to reply back asap.