View on GitHub


A jQuery plugin to render Handlebars.js templates into elements

Download this project as a .zip file Download this project as a tar.gz file


A jQuery plugin to render Handlebars.js templates into elements.

Template scripts are retrieved through AJAX, precompiled and cached.


Version 1.1 available.

Getting Started

Each jQuery object has a render method that:


<p>{{ field1 }}, {{ field2 }}</p>
// will fetch <template.handlebars> and render to the DOM element whose id is "content"
$('#content').render('template', {
    field1: 'Hello',
    field2: 'world!'

The first argument to the render method is a template name. The plugin builds the template path to fetch from this name by prepending a base path and appending a file name extension. The default base path is the empty string, while the default extension is .handlebars. To configure them differently use the jQuery.handlebars method:

    templatePath: 'path/to/templates',
    templateExtension: 'hbs'

// now this will fetch <path/to/templates/content.hbs>
$('#some-element').render('content', {
    // ...

The second argument to the render method is of course the context to use in Handlebars to render the template.

Helpers and partials

When using this plugin you can use the Handlebars namespace normally if you want; this allows you to register helpers and partials.

For example:

{{! I'm using a custom "salute" helper }}
<p>{{salute what }}</p>

{{! I'm using a custom "csv" block helper }}
{{#csv array }}{{ this }}{{/csv}}
Handlebars.registerHelper('salute', function (what) {
    return 'Hello, ' + what + '!';

Handlebars.registerHelper('csv', function (array, options) {
    return (element) {
        return options.fn(element);
    }).join(', ');

$('#content').render('content', {
    what: 'world',
    array: [1, 2, 3]

The plugin also supports fetching and registering partials. You only need to configure the base path and filename extension for the partial files in the jQuery.handlebars method:

    partialPath: 'partials',
    partialExtension: 'partial'

Then you can register a partial using the partial action of the jQuery.handlebars method:

/* based on configured settings, this will fetch the <partials/element.partial>
    file and register it as a partial */
$.handlebars('partial', 'element');

At this point, assuming you have the following partials/element.partial file:

<li>{{ this }}</li>

you can access it in your templates normally:

{{#each array }}
    {{> element }}
$('#content').render('template', {
    array: ['first', 'second', 'last']

As a shorthand you can register all the partials at initialization time using the partials configuration setting:

    templatePath: 'templates',
    partialPath: 'partials',
    partials: ['header', 'footer', 'user', 'another-partial', 'another-one']


MIT. Copyright 2013 Alberto La Rocca.