Templating with Handlebars

As we discussed in Chapter 5, Adding and Modifying Elements with Views, using templates to render your View's HTML offers many benefits. While you can simply use Underscore's template function, if you want a more powerful templating language there are many different libraries to choose from. For this chapter, we are going to use Handlebars (http://handlebarsjs.com/) as our templating engine. Other libraries you may want to consider include Mustache (https://github.com/janl/mustache.js), Embedded JS (http://embeddedjs.com/), or Hogan.js (http://twitter.github.io/hogan.js/).

Handlebars, which was created from another templating library (Mustache), offers a significant amount of in-template logic in the form of "helper". For instance, here's a Handlebars template that uses an "each" helper and an "if" helper to render a list of last names prefaced with either "Mr." or "Ms.," depending on the person's gender:

<ul>
    {{#each people}}
    <li>
        {{#if this.isMale}}Mr.{{else}}Ms.{{/if}} {{this.lastName}}
    </li>
    {{/each}}
</ul>

Handlebars also allows you to define your own custom helpers, which makes it very extensible. These helpers are so flexible that you could create an entire sub-language within your templates if you so desire.

Once you have a template written, you can either include it directly in your JavaScript code (wrapped in quotation marks to make it a valid string), or you can store it in a separate file and use RequireJS or a similar tool to bring it in. Thereafter, it's a simple matter of compiling the template and writing a View render method that uses this template, as follows:

var template = '<ul>' +
    '{{#each people}}' +
    '<li>' +
        '{{#if this.isMale}}Mr.{{else}}Ms.{{/if}} {{this.lastName}}' +
    '</li>' +
    '{{/each}}' +
'</ul>';
var compiledTemplate = Handlebars.compile(template);
var TemplatedView = Backbone.View.extend({
    render: function() {
        var templatedHtml = compiledTemplate(this.model.toJSON());
        this.$el.html(templatedHtml);
        return this;
    }
});
new TemplatedView({
    model: new Backbone.Model({isMale: 'true', lastName: 'Smith'})
}).render().$el.html(); // will be "Mr. Smith"
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.71.211