Template helpers in backbone js - Learning BackboneJs
This entry is part 10 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
Templates make your code look more neat and clean and helps in a lot of other ways.
Template helpers
So far we are using embedded templates in our HTML file ie
<script id="personTemplate" type="text/template">
<strong><%= name %></strong> (<%= age %>) - <%= occupation %>
</script>
In our view we are calling this template like this:
template: _.template( $('#personTemplate').html()),
One good thing over here is we can define a template helpers in backbone js (as a global function) and optimize our code like this.
var template = function(id){
return _.template( $('#' + id).html() );
};
Now in personView call the template by just calling:
template: template('personTemplate'),
Just defining a simple function can make our life much easier as we have to call many templates in real our applications. That’s all for this lesson. Will come back soon with an important topic ie namespacing.
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.