This entry is part 6 of 14 in the series for A Complete Guide for Learning Backbone Js
- Introduction and Installation
- 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
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:
What was the problem
The problem is this code is:
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.
So we introduced a new line i.e.,
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
and we assigned it to
Now backbone js will compile it and define a function behind the scenes. Next modification that we did was:
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:
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:
Fire up the console and fire these commands
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.
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.
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.