Handlebars built-in helpers: if, each, and with

Use the built-in if, unless, each, and with helpers for conditional rendering and iteration.

🎯 Introduction

In this article, you will learn four commonly used Handlebars helpers: if, unless, each, and with. These essential tools add conditional rendering and iteration to your templates.


🧱 Conditional rendering with if

if determines whether to render a block based on a condition.

index.js
const Handlebars = require('handlebars');

const template = `
{{#if isLogin}}
    <p>Welcome back, {{username}}</p>
{{/if}}
`;

const compiled = Handlebars.compile(template);
const html = compiled({ isLogin: true, username: 'Ming' });

console.log(html);

Output:

<p>Welcome back, Ming</p>

Use {{else}} when you need an alternative branch:

{{#if isLogin}}
    <p>Welcome back, {{username}}</p>
{{else}}
    <p>Please sign in first</p>
{{/if}}
Handlebars if tests whether a value is truthy or falsy. It treats 0, '', null, undefined, and [] as falsy.

✨ Inverting a condition with unless

unless is the inverse of if: it renders its block only when the condition is falsy.

{{#unless isLogin}}
    <p>You are not signed in</p>
{{/unless}}

This is equivalent to the following if block:

{{#if isLogin}}
{{else}}
    <p>You are not signed in</p>
{{/if}}
Use unless to show a message when a condition is not met. It is more concise than if with else for this case.

💡 Iterating with each

each iterates over arrays or objects.

Iterating over an array

index.js
const template = `
<ul>
    {{#each list}}
        <li>{{this}}</li>
    {{/each}}
</ul>
`;

const compiled = Handlebars.compile(template);
const html = compiled({ list: ['HTML', 'CSS', 'JavaScript'] });

console.log(html);

Output:

<ul>
    <li>HTML</li>
    <li>CSS</li>
    <li>JavaScript</li>
</ul>

Inside each, this refers to the current item.

Iterating over an array of objects

<ul>
    {{#each users}}
        <li>{{name}} - {{age}} years old</li>
    {{/each}}
</ul>

Input:

{ users: [{ name: 'Ming', age: 18 }, { name: 'Hong', age: 20 }] }

Output:

<ul>
    <li>Ming - 18 years old</li>
    <li>Hong - 20 years old</li>
</ul>

Handling an empty array

Use {{else}} to display a message when the array is empty:

<ul>
    {{#each users}}
        <li>{{name}}</li>
    {{else}}
        <li>No users yet</li>
    {{/each}}
</ul>

⚖️ @index and @key inside each

When iterating over an array, use @index to get the current index:

<ul>
    {{#each list}}
        <li>{{@index}}. {{this}}</li>
    {{/each}}
</ul>

Output:

<ul>
    <li>0. HTML</li>
    <li>1. CSS</li>
    <li>2. JavaScript</li>
</ul>

When iterating over an object, use @key to get the current property name:

<ul>
    {{#each user}}
        <li>{{@key}}: {{this}}</li>
    {{/each}}
</ul>

🧰 Changing context with with

with changes the current context to a specified object so you can avoid repeating its name.

index.js
const template = `
{{#with user}}
    <p>Name: {{name}}</p>
    <p>Age: {{age}}</p>
{{/with}}
`;

const compiled = Handlebars.compile(template);
const html = compiled({
    user: { name: 'Ming', age: 18 }
});

console.log(html);

Output:

<p>Name: Ming</p>
<p>Age: 18</p>

Inside {{#with user}}, {{name}} and {{age}} read directly from the user object.

If the value passed to with is falsy, such as null or undefined, its block is not rendered.

❓ Questions and answers

Q1: Can Handlebars if evaluate complex expressions?

No. Handlebars keeps complex logic out of templates. You cannot write JavaScript expressions such as a > b or a && b directly in an if condition. Compute complex conditions before passing in the data, or use a custom helper.

Q2: Can I access object properties with {{name}} inside each?

Yes. When iterating over an array of objects, the current item becomes the context, so {{name}} reads that item's name property.

Q3: How does with differ from writing user.name directly?

Both access the same data. with simply makes the template more concise by reducing repeated prefixes when you use several properties of an object.

Q4: Does an empty array cause an error in each?

No. The loop renders no items. Use {{else}} to display a helpful message instead.


🧪 Exercise

Write a Handlebars template for the following data:

index.js
const data = {
    isVip: true,
    products: [
        { name: 'Apple', price: 5 },
        { name: 'Banana', price: 3 }
    ]
};

// Write your template here
// Requirements:
// 1. If isVip is true, display "VIP exclusive"
// 2. Use each to render products with their names and prices

🎉 You have learned the built-in Handlebars helpers! Next, we will explore partials, which let you reuse templates much like components.