First, you need to install Handlebars to your Express.js application using npm:
npm install express-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');
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>
To use a template, render it in your Express.js routes:
app.get('/', (req, res) => {
res.render('home', { title: 'Home Page' });
});
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>
Solutions:
1. Create footer.handlebars
in partials
directory:
<footer>
<p>© {{year}} My Website</p>
</footer>
Include in main layout:
{{> footer}}
app.get('/contact', (req, res) => {
res.render('contact', { title: 'Contact Page', year: new Date().getFullYear() });
});
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.