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


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 %>

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.