Sling Academy
Home/Node.js/Node.js: How to use Handlebars to render HTML templates

Node.js: How to use Handlebars to render HTML templates

Last updated: December 28, 2023

Handlebars is a popular templating engine that is used to create dynamic HTML templates. It extends the Mustache templating language by adding powerful features like helpers and more advanced block expressions. Handling templates with Handlebars in Node.js simplifies the process of sending dynamic HTML content to the client. In this tutorial, we will explore the basics of setting up Handlebars with Node.js and how to use it to render HTML templates effectively.

Getting Started with Handlebars

To begin, you’ll need to have Node.js installed on your system. Once you have Node.js set up, you can start by creating a new project folder and initializing it with npm:

mkdir my-handlebars-project
cd my-handlebars-project
npm init -y

Next, install express and express-handlebars which is an Handlebars view engine for Express:

npm install express express-handlebars

Now, you’ll set up a basic Express server that uses Handlebars as the templating engine:

const express = require('express');
const { engine } = require('express-handlebars');

const app = express();

app.engine('handlebars', engine());
app.set('view engine', 'handlebars');
app.set('views', './views');

app.get('/', (req, res) => {
    res.render('home');
});

app.listen(3000);

Here, we define the view engine as ‘handlebars’ using the ‘engine’ function from ‘express-handlebars’ package. We also set the default directory for your templates in ‘views’ folder.

Creating Handlebars Templates

Templates in Handlebars have the ‘.handlebars’ extension. Let’s create a basic template named ‘home.handlebars’ inside the ‘views’ directory:

<!DOCTYPE html>
<html>
<head>
    <title>My Handlebars Template</title>
</head>
<body>
    <h1>{{title}}</h1>
    <p>{{message}}</p>
</body>
</html>

This template contains placeholders for title and message which are dynamic values passed from the server.

Passing Data to Templates

Back in your server file, modify the route handler to pass data to the ‘home’ template:

app.get('/', (req, res) => {
    res.render('home', {
        title: 'Handlebars Tutorial',
        message: 'Hello, Handlebars!'
    });
});

Now, when you visit the root of your server, you should see the rendered HTML with your data.

Using Partials

Partials are reusable template fragments. To demonstrate, create a partial named ‘navbar.handlebars’ in a ‘views/partials’ folder:

<nav>
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
    </ul>
</nav>

Register partials in your server:

const hbs = engine();
hbs.handlebars.registerPartial('navbar', fs.readFileSync('./views/partials/navbar.handlebars', 'utf8'));

app.engine('handlebars', hbs);

To use the navbar partial in your ‘home.handlebars’ template, add:

{{> navbar}}

Now, navbar will appear wherever you include it in the template.

Advanced Usage: Helpers

Handlebars helpers allow you to perform custom logic within your templates. For instance, you can write a helper to uppercase a string:

hbs.handlebars.registerHelper('shout', (text) => {
    return text.toUpperCase();
});

Use the helper in your ‘home.handlebars’ template:

{{shout title}}

This will render the title in uppercase letters.

Conclusion

In this article, we’ve introduced the basics of setting up and using Handlebars with Node.js. You’ve learned how to create templates, partials, and helpers which are essential components for building robust HTML templates. With these tools, you’re now equipped to develop dynamic web applications with Node.js and Handlebars.

Next Article: How to Create Middleware in Express.js

Previous Article: How to handle CORS in Express JS

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates