Getting a Handle on Handlebars: Mastering HTML Templates

Mattjunk
2 min readJan 1, 2024

Handlebars.js, a compelling extension of Mustache template language, allows developers to create semantic HTML templates with minimal fuss. This article dives into the essentials of Handlebars, focusing on its syntax and practical use cases with code examples, assuming you’re already familiar with its setup and installation.

1. Basic Syntax of Handlebars

Handlebars templates look like regular HTML but with embedded Handlebars expressions, denoted by double curly braces {{}}. These expressions are placeholders for values that you'll define in your JavaScript.

2. Creating a Simple Template

Let’s start with a basic example. Suppose you want to display a user’s name:

<script id="user-template" type="text/x-handlebars-template">
<p>Hello, {{name}}!</p>
</script>

Here, {{name}} is a placeholder that Handlebars will replace with data provided.

3. Compiling and Using the Template

After writing your template, compile and use it in JavaScript:

var templateSource = document.getElementById('user-template').innerHTML;
var template = Handlebars.compile(templateSource);
var context = { name: 'Alice' };
var html = template(context);
document.body.innerHTML = html;

This results in <p>Hello, Alice!</p> being rendered on the webpage.

4. Iterating Over Lists

Handlebars simplifies the process of rendering lists with the {{#each}} helper:

<script id="users-template" type="text/x-handlebars-template">
<ul>
{{#each users}}
<li>{{this}}</li>
{{/each}}
</ul>
</script>

Using an array with this template:

var usersTemplate = Handlebars.compile(document.getElementById('users-template').innerHTML);
var usersHtml = usersTemplate({ users: ['Alice', 'Bob', 'Charlie'] });
document.body.innerHTML = usersHtml;

This code will generate a list of user names.

5. Implementing Conditional Logic

Handlebars also supports conditional statements using {{#if}}:

<script id="conditional-template" type="text/x-handlebars-template">
{{#if loggedIn}}
<p>Welcome back!</p>
{{else}}
<p>Please log in.</p>
{{/if}}
</script>

Along with its JavaScript implementation:

var conditionalTemplate = Handlebars.compile(document.getElementById('conditional-template').innerHTML);
var conditionalHtml = conditionalTemplate({ loggedIn: true });
document.body.innerHTML = conditionalHtml;

6. Crafting Custom Helpers

Handlebars allows the creation of custom helpers for more complex logic. For instance, a greeting helper:

Handlebars.registerHelper('greet', function(name) {
return 'Hello, ' + name + '!';
});
var customHelperTemplate = Handlebars.compile('{{greet user}}');
document.body.innerHTML = customHelperTemplate({ user: 'Alice' });

--

--