Express.js / Express.js with Template Engines

Creating Reusable Templates with Handlebars

Handlebars is a powerful template engine that allows for the creation of semantic templates. This tutorial will guide you through setting up Handlebars in an Express.js applicatio…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers using template engines like EJS, Pug, and Handlebars to render dynamic views.

1. Introduction

  • The goal of this tutorial is to guide you on how to set up Handlebars in an Express.js application and create reusable templates. Handlebars is a simple-to-use, powerful templating engine that lets you build semantic templates effectively.
  • By the end of this tutorial, you will learn how to install and set up Handlebars, create and use templates, and understand how to make your templates reusable and modular.
  • Prerequisites: Basic knowledge of JavaScript and Node.js would be beneficial. Familiarity with Express.js would also be helpful.

2. Step-by-Step Guide

2.1 Installing Handlebars

First, you need to install Handlebars to your Express.js application using npm:

npm install express-handlebars

2.2 Setting Up Handlebars

After installation, set up Handlebars in your application:

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

const app = express();
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

2.3 Creating Templates

Create a views directory in your application root. Inside the views, create a layouts directory. Put your main Handlebars layout file (main.handlebars) inside the layouts directory.

<!DOCTYPE html>
<html>
<head>
    <title>{{title}}</title>
</head>
<body>
    {{{body}}}
</body>
</html>

2.4 Using Templates

To use a template, render it in your Express.js routes:

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

3. Code Examples

3.1 Example - Creating a Reusable Header Template

Create a partials directory in your views directory. Create a new file called header.handlebars inside partials:

// header.handlebars
<header>
    <h1>{{title}}</h1>
    <nav>
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/about">About</a></li>
        </ul>
    </nav>
</header>

To use this template, include it in your main layout:

// main.handlebars
<!DOCTYPE html>
<html>
<head>
    <title>{{title}}</title>
</head>
<body>
    {{> header}}
    {{{body}}}
</body>
</html>

4. Summary

5. Practice Exercises

  1. Create a reusable footer template that includes a copyright notice. Include this footer in your main layout.
  2. Create a 'contact' page using Handlebars and Express.js. Include your header and footer templates in this page.
  3. Create a template for a blog post. This template should include the post title, date, author, and content.

Solutions:
1. Create footer.handlebars in partials directory:

<footer>
    <p>&copy; {{year}} My Website</p>
</footer>

Include in main layout:

{{> footer}}
  1. In your Express.js routes:
app.get('/contact', (req, res) => {
    res.render('contact', { title: 'Contact Page', year: new Date().getFullYear() });
});
  1. Create post.handlebars:
<article>
    <h2>{{title}}</h2>
    <p>By {{author}} on {{date}}</p>
    <div>{{{content}}}</div>
</article>

Use this template:

app.get('/post', (req, res) => {
    res.render('post', { title: 'My Post', author: 'Me', date: 'Today', content: 'This is my post.' });
});

Remember, practice makes perfect. Keep experimenting with Handlebars to become proficient at it.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help