JS templating system with Backbone.js

copenndthagen picture copenndthagen · Mar 19, 2012 · Viewed 8.8k times · Source

I am looking at some good templating systems to be used alongwith an MVC framework like Backbone.js

I am aware of one such system (jQuery Templating). However, the same has been discontinued for some reasons and hence I am looking at some other good options.

Please suggest something which is flexible enough from a view perspective. (e.g. a dynamic view with enabled/disabled button based on some logic, tabular data with different styles based on some logic, etc)

Answer

jcreamer898 picture jcreamer898 · Mar 19, 2012

I really like Handlebars.js...

Here's some JavaScript...

var HandlebarsView = Backbone.View.extend({
    el: '#result'
    initialize: function(){
        this.template = Handlebars.compile($('#template').html());
    },
    render: function(){
        var html = this.template(this.model.toJSON());
        this.$el.html(html);
    }
});

var HandlebarsModel = Backbone.Model.extend({});

var model = new HandlebarsModel({
   name: 'Joe Schmo',
   birthday: '1-1-1970',
   favoriteColor: 'blue'
});

var view = new HandlebarsView({
    model: model
});
view.render();

Then the html...

 <div id="result">
 </div>
 <script id="template" type="text/html">
    <div>Name:{{name}} Birthday: {{birthday}} Favorite Color: {{favoriteColor}} </div>
 </script>

Give that a shot!