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.
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
Let's start by setting up a basic Express application that uses Handlebars as the templating engine.
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}`);
});
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>
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.
Handlebars uses double curly braces {{ }} for embedding expressions. Let's explore some common features of Handlebars:
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.
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}}
You can iterate over arrays using the each helper.
<ul>
{{#each items}}
<li>{{this}}</li>
{{/each}}
</ul>
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>
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>
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>© 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' });
});
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.