Using Handlebars with Backbone

Joseph at SwiftOtter picture Joseph at SwiftOtter · Jan 31, 2012 · Viewed 46.6k times · Source

I am learning Backbone/Handlebars/Require. I have looked all over online and on SO - are there any tutorials or websites that you can direct me to that would provide helpful information for using using handlebars instead of underscore?

Answer

SimplGy picture SimplGy · Jun 1, 2012

Using handlebars.js instead of underscore templating is pretty straightforward. Check out this example:

https://cdnjs.com/libraries/backbone.js/tutorials/what-is-a-view (scroll to the "Loading a Template" section)

SearchView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    render: function(){
        // Compile the template using underscore
        var template = _.template( $("#search_template").html(), {} );
        // Load the compiled HTML into the Backbone "el"
        this.el.html( template );
    }
});

Basically, the convention in backbone is to build your html in a render function. The use of templating engine is left completely up to you (which I like about Backbone). So you'd just change it to:

SearchView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    render: function(){
        // Compile the template using Handlebars
        var template = Handlebars.compile( $("#search_template").html() );
        // Load the compiled HTML into the Backbone "el"
        this.el.html( template );
    }
});

Since you're using require.js, you can make Handlebars a dependency at the top of your module. I'm pretty new to this, but it sounds like the learning to focus on would be Backbone.js patterns and require.js usage.