How to use the Handlebars templating engine in an Express.js application



Image not found!!

Handlebars is a popular templating engine for JavaScript that allows you to create dynamic HTML templates. When used with Express.js, Handlebars enables you to render dynamic content on the server and send it to the client. Here's a step-by-step guide on how to use Handlebars in an Express.js application:

Step 1: Install Handlebars and Express

Make sure you have Node.js and npm installed. Then, in your project directory, run the following commands to install Handlebars and Express:

bash
npm install express handlebars

Step 2: Set up your project structure

Create the basic structure for your Express.js application. Create files like app.js (or any other entry point) and a folder named views to store your Handlebars templates.

go
project-root/ |- views/ | |- index.handlebars |- app.js |- package.json

Step 3: Configure Express to use Handlebars

In your app.js file, set up Express to use Handlebars as the view engine:

javascript
const express = require('express'); const exphbs = require('express-handlebars'); const app = express(); // Set Handlebars as the view engine app.engine('handlebars', exphbs()); app.set('view engine', 'handlebars'); // Set the path to the 'views' directory app.set('views', './views'); // Define a route to render the Handlebars template app.get('/', (req, res) => { // The second parameter of res.render is an object containing data to be passed to the template res.render('index', { title: 'Express with Handlebars' }); }); // Start the server const port = 3000; app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });

Step 4: Create a Handlebars template

Create a file named index.handlebars inside the views folder with the following content:

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> <h1>{{ title }}</h1> </body> </html>

Step 5: Run your Express.js application

Now, run your Express.js application:

bash
node app.js

Visit http://localhost:3000 in your browser, and you should see the rendered HTML with the dynamic content from the Handlebars template.

This is a basic setup to get you started with Handlebars in an Express.js application. You can explore more features of Handlebars, such as partials, helpers, and more, to build more complex and dynamic templates.