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:
Make sure you have Node.js and npm installed. Then, in your project directory, run the following commands to install Handlebars and Express:
bashnpm install express handlebars
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.
goproject-root/
|- views/
| |- index.handlebars
|- app.js
|- package.json
In your app.js
file, set up Express to use Handlebars as the view engine:
javascriptconst 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}`);
});
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>
Now, run your Express.js application:
bashnode 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.