Handlebars introduction

Handlebars is a templating framework. Using Handlebars is as easy as shown below:

// A JavaScript object is passed to a Handlebars template:
var model = {
name: 'Dan'
};

The HTML template file will be:

<div>
Hi {{ name }}!
</div>

This file will render to a browser as “Hi Dan!”.

Of course, there’s a lot more that you can do than just this! Handlebars also supports conditional statements:

var model = {
name: 'Dan',
description: 'Dan is a web developer..'
};

The HTML part will be:

<div>
Hi {{ name }}!<br/><br/>
{{#if description}}
<p>{{description}}</p>
{{/if}}
</div>

Using an if block helper, you can check for true conditionals and only display HTML and/or data if the condition is true. Of course you can do vice-verse too and display HTML only if a condition is false:

var model = {
name: 'World'
};

The HTML part will be:

<div>
Hi {{ name }}!<br/><br/>
{{#unless description}}
<p>NOTE: no description found.</p>
{{/if}}
</div>

You can use both if and else as well as unless the same way you would use conditional if/else in other programming languages.

You can also build special custom function to perform custom logic. If it is the case then you should place the logic from views into a helper file and reuse it.

These helper files can be registered globally and made available to every template file, or they can be defined per view and passed to the template on an as-needed basis as part of the viewModel .

Leave a Reply