Here's an example of how to use the Handlebars template engine with an Express.js application.
Step-by-Step Guide¶
- Set up the project: First, create a new directory for your project and initialize a new Node.js project.
mkdir express-handlebars-example
cd express-handlebars-example
npm init -y
- Install dependencies:
Install Express.js and Handlebars along with the
express-handlebars
package.
npm install express express-handlebars
- Create the project structure: Create the following folders and files:
express-handlebars-example/
├── node_modules/
├── views/
│ ├── layouts/
│ │ └── main.handlebars
│ └── home.handlebars
├── app.js
├── package.json
- Set up the Express.js application with Handlebars:
Edit
app.js
to configure the Express.js application to use Handlebars.
// app.js
const express = require('express');
const exphbs = require('express-handlebars');
const app = express();
// Set up Handlebars as the template engine
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
// Define a route
app.get('/', (req, res) => {
res.render('home', { title: 'Home Page', message: 'Welcome to Handlebars with Express!' });
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
- Create the main layout:
Create a
main.handlebars
file in theviews/layouts
directory. This will be the main layout template that other views will extend.
<!-- views/layouts/main.handlebars -->
<!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>
{{{body}}}
</body>
</html>
- Create the home view:
Create a
home.handlebars
file in theviews
directory. This will be the view that renders when the user visits the home page.
<!-- views/home.handlebars -->
<h1>{{message}}</h1>
- Run the application: Start the application by running the following command:
node app.js
- Test the application:
Open your browser and visit
http://localhost:3000
. You should see the message "Welcome to Handlebars with Express!" displayed on the home page.
Explanation¶
express-handlebars
package: This package integrates Handlebars with Express.js, allowing you to use.handlebars
files as templates.- Layouts: The
main.handlebars
file serves as a layout template, which other views can extend. The{{{body}}}
placeholder is where the content of the child views will be rendered. - Views: The
home.handlebars
file is a view that contains the specific content to be rendered for the home page. The{{title}}
and{{message}}
placeholders are replaced with the values passed from the route handler.
This setup provides a basic but functional example of using Handlebars with Express.js. You can extend this by adding more routes, views, and partials as needed for your application.