Backbone Handlebars Rendering

2013

Using handlebars templates with backbone views is a good foundation that provides a lot of flexibility for managing and rendering views within an app. Here's a quick rundown on how to setup a base view in backbone to render your templates.

Assuming you've compiled your templates by following the handlebars docs, you'll have access to your templates by name through the Handlebars.templates object.

      
  Handlebars.templates['template-name']()
      
    

The simplest form of the render function will insert the template into the view element, and then return the element.

      
  render: function(){
    this.$el.html(Handlebars.templates['template-name']());
    return this.$el;
  }
      
    

To set this up as a base view, and make the name of your templates dynamic, extend Backbone's base view.

      
  // setup namespaces for your app
  var App = { Views: {} };

  App.Views.Base = Backbone.View.extend({
    templateName: null,

    render: function(){
      this.$el.html(Handlebars.templates[this.templateName]());
      return this.$el;
    }
  });

  // defining a class with a template
  App.Views.MyView = App.Views.Base.extend({
    templateName: 'my-template'
  });
      
    

Now that the base view setup to render a template by name, there's only a couple more adjustments needed, optional templates and passing data. Making templates optional is useful since there won't necessarily be a template for every view, and passing data into a template is easily accomplished using a Backbone model.

      
  App.Views.Base = Backbone.View.extend({
    templateName: null,

    render: function(){
      var data;

      if(this.templateName !== null){

        if(this.model !== null){
          data = this.model.toJSON()
        }else{
          data = {}
        }

        this.$el.html(Handlebars.templates[this.templateName](data))
      }

      return this.$el;
    }
  });

  App.Views.MyView = App.Views.Base.extend({
    templateName: 'my-template'
  });

  var myView = new App.Views.MyView({
    model: new Backbone.Model({
      awesome: true
    })
  });

  $('#container').html(myView.render());
      
    

This base view is available in a gist.

comments powered by Disqus