codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🚂

Express.js

10 / 76 topics
7Using Templates with Express.js8EJS (Embedded JavaScript) Templates9Pug (formerly Jade) Templates10Handlebars Templates
Tutorials/Express.js/Handlebars Templates
🚂Express.js

Handlebars Templates

Updated 2026-04-20
3 min read

Introduction

In this tutorial, we will explore how to use Handlebars templates in an Express.js application. Handlebars is a simple templating language that allows you to generate HTML dynamically by embedding expressions within your template files. It's widely used due to its flexibility and ease of integration with Node.js applications.

Setting Up Your Environment

Before diving into Handlebars, ensure you have Node.js installed on your machine. You can download it from the official website. Once Node.js is installed, create a new directory for your project and initialize it using npm:

mkdir express-handlebars-app
cd express-handlebars-app
npm init -y

Next, install Express.js and Handlebars:

npm install express express-handlebars

Basic Setup

Let's start by setting up a basic Express application that uses Handlebars as the templating engine.

1. Create the Application File

Create a file named app.js in your project directory and add the following code:

const express = require('express');
const exphbs = require('express-handlebars');

const app = express();
const PORT = process.env.PORT || 3000;

// Set up Handlebars as the templating engine
app.engine('.hbs', exphbs({ extname: '.hbs' }));
app.set('view engine', '.hbs');

// Define a route
app.get('/', (req, res) => {
    res.render('home', { title: 'Welcome to Express with Handlebars' });
});

// Start the server
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

2. Create the Template File

Create a directory named views in your project root and inside it, create a file named home.hbs. Add the following content to this file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ title }}</h1>
    <p>This is a simple Handlebars template in an Express.js application.</p>
</body>
</html>

3. Run the Application

Start your server by running the following command:

node app.js

Navigate to http://localhost:3000 in your web browser, and you should see the message "Welcome to Express with Handlebars" displayed.

Understanding Handlebars Syntax

Handlebars uses double curly braces {{ }} for embedding expressions. Let's explore some common features of Handlebars:

1. Variables

Variables are embedded using double curly braces. In the previous example, {{ title }} is a variable that gets replaced with the value passed from the server.

2. Conditionals

Handlebars supports basic conditional logic using the if, unless, and with helpers.

{{#if user}}
    <p>Welcome back, {{user.name}}!</p>
{{else}}
    <p>Please log in.</p>
{{/if}}

3. Loops

You can iterate over arrays using the each helper.

<ul>
    {{#each items}}
        <li>{{this}}</li>
    {{/each}}
</ul>

4. Partials

Partials are reusable template snippets that can be included in other templates.

Create a file named _header.hbs in the views directory:

<header>
    <h1>{{ title }}</h1>
</header>

Include this partial in your main template using the >partialName syntax:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
</head>
<body>
    {{> _header}}
    <p>This is a simple Handlebars template in an Express.js application.</p>
</body>
</html>

Advanced Features

1. Custom Helpers

Handlebars allows you to define custom helpers that can be used within your templates.

Add the following code to app.js to register a custom helper:

const exphbs = require('express-handlebars');

// Register a custom helper
exphbs.registerHelper('greet', function(name) {
    return `Hello, ${name}!`;
});

// Set up Handlebars as the templating engine
app.engine('.hbs', exphbs({ extname: '.hbs' }));

Use this helper in your template:

<p>{{ greet "World" }}</p>

2. Layouts

Handlebars doesn't have built-in support for layouts, but you can achieve similar functionality by using partials or a layout middleware.

Create a file named layout.hbs in the views directory:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
</head>
<body>
    {{> _header}}
    {{{body}}}
    <footer>
        <p>&copy; 2023 Your Company</p>
    </footer>
</body>
</html>

Modify your home.hbs to use the layout:

{{#*inline "body"}}
    <p>This is a simple Handlebars template in an Express.js application.</p>
{{/inline}}

Update your route to render with the layout:

app.get('/', (req, res) => {
    res.render('home', { title: 'Welcome to Express with Handlebars' }, { layout: 'layout' });
});

Best Practices

  1. Keep Templates Simple: Templates should focus on presentation logic only. Business logic should be handled in your server-side code.
  2. Use Partials for Reusability: Break down complex templates into smaller, reusable partials to maintain clean and organized code.
  3. Leverage Custom Helpers: Use custom helpers to encapsulate common template logic and make your templates more readable.
  4. Error Handling: Always handle errors gracefully in your templates to avoid exposing sensitive information.

Conclusion

Handlebars is a powerful templating engine that integrates seamlessly with Express.js, providing a flexible way to generate dynamic HTML content. By following the best practices outlined in this tutorial, you can create maintainable and efficient web applications using Handlebars in Express.js.


PreviousPug (formerly Jade) TemplatesNext Serving Static Files

Recommended Gear

Pug (formerly Jade) TemplatesServing Static Files