Custom Handlebars helpers: Extending templates
🎯 Introduction
In this article, you will learn to write custom helpers. Handlebars templates cannot contain complex JavaScript expressions, but applications often need formatting, conditions, and calculations. Helpers encapsulate that logic in reusable functions you can call from templates, much like an API.
🧱 Why use custom helpers?
Consider a common task: formatting a price as “¥xx.xx”.
You cannot write {{price.toFixed(2)}} because Handlebars does not support that expression. Instead, write a helper:
Handlebars.registerHelper('formatPrice', function (price) {
return '¥' + price.toFixed(2);
});
Use it in a template like this:
<p>Price: {{formatPrice price}}</p>
With { price: 19.9 }, the output is:
<p>Price: ¥19.90</p>
✨ Registering a simple helper
const Handlebars = require('handlebars');
// Register the helper
Handlebars.registerHelper('uppercase', function (str) {
return str.toUpperCase();
});
// Use the helper
const template = '<p>{{uppercase name}}</p>';
const compiled = Handlebars.compile(template);
const html = compiled({ name: 'hello' });
console.log(html);
Output:
<p>HELLO</p>
The helper's first parameter receives the value passed from the template. You can accept additional parameters after it.
💡 Helpers with multiple arguments
Handlebars.registerHelper('join', function (arr, separator) {
return arr.join(separator);
});
Template:
<p>Tags: {{join tags ", "}}</p>
Input:
{ tags: ['Frontend', 'Handlebars', 'template engine'] }
Output:
<p>Tags: Frontend, Handlebars, template engine</p>
⚖️ Writing a comparison helper
The built-in if helper does not evaluate JavaScript expressions directly. Write an eq helper to test equality:
Handlebars.registerHelper('eq', function (a, b) {
return a === b;
});
Template:
{{#if (eq status "success")}}
<p>Operation successful</p>
{{/if}}
Input:
{ status: 'success' }
Output:
<p>Operation successful</p>
() to pass its result to another helper, such as if.🛠 Common custom helper examples
1. Formatting a date
Handlebars.registerHelper('formatDate', function (date) {
const d = new Date(date);
return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
});
2. Checking whether an array is empty
Handlebars.registerHelper('isEmpty', function (arr) {
return !arr || arr.length === 0;
});
3. Adding one to an index
Handlebars.registerHelper('addOne', function (index) {
return index + 1;
});
Template:
<ul>
{{#each list}}
<li>{{addOne @index}}. {{this}}</li>
{{/each}}
</ul>
🪤 Understanding this in helpers
Inside a helper function, this refers to the current template context. Pay attention to context changes when working with block helpers.
Handlebars.registerHelper('showContext', function () {
console.log(this);
});
Simple helpers usually do not need this, but it is useful to know what it refers to.
❓ Questions and answers
Q1: Can I write {{a + b}} in a Handlebars template?
No. Handlebars does not support JavaScript expressions directly. Use a custom helper instead, such as {{add a b}}.
Q2: How does a helper differ from a partial?
A helper is JavaScript logic that returns a value. A partial is a template fragment that renders HTML. Helpers process data; partials reuse structure.
Q3: Can a custom helper return HTML?
Yes, but returned strings are escaped by default. To output raw HTML, wrap the value in new Handlebars.SafeString(html).
Q4: How should I name helpers?
Use camelCase and avoid names already used by built-in helpers, such as if and each.
🧪 Exercise
Write a formatDate helper and render the following data:
const data = {
createdAt: '2024-10-01T08:00:00.000Z'
};
// Register the formatDate helper here
// Format the date as YYYY-MM-DD
🎉 You have learned how to write custom Handlebars helpers! Next, we will explore precompilation and the runtime for more efficient production use.
