Introduction to Express-Handlebars
Express-Handlebars is a powerful templating engine that seamlessly integrates with Express.js, providing robust and dynamic HTML rendering capabilities from your Node.js server. It enhances the user experience by allowing developers to generate HTML with dynamic content efficiently.
Setting Up Express-Handlebars
First, ensure you have Node.js and npm installed. To get started, install the necessary packages.
npm install express express-handlebars
Basic Setup
We’ll start with a basic setup to initialize our Express application with Handlebars as the templating engine.
const express = require('express');
const exphbs = require('express-handlebars');
const app = express();
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.get('/', function (req, res) {
res.render('home');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Creating Views
Create a directory named views
and add a file called home.handlebars
inside it:
Home Page
Welcome to Express-Handlebars
Passing Data to Templates
One of the major features of Handlebars is its ability to accept dynamic data, which you can pass to your templates as follows:
app.get('/about', function (req, res) {
res.render('about', { title: 'About Us', content: 'This is the about us page.' });
});
Example of about.handlebars
{{title}}
{{title}}
{{content}}
Using Partials
Partials allow you to define reusable HTML snippets. Here’s how you can create and use partials:
// Registering partials
const exphbs = require('express-handlebars');
const app = express();
app.engine('handlebars', exphbs({
partialsDir: __dirname + '/views/partials'
}));
app.set('view engine', 'handlebars');
app.get('/contact', function (req, res) {
res.render('contact', { title: 'Contact Us' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
// In a contact.handlebars file
{{title}}
{{> header }}
{{title}}
{{> footer }}
Example of Partials
Create a directory named partials
inside views
and add two files: header.handlebars
and footer.handlebars
.
Helpers
Handlebars helpers are functions that can be used in templates to perform certain actions. Here’s how to register a helper:
app.engine('handlebars', exphbs({
helpers: {
shout: function (msg) { return msg.toUpperCase(); }
}
}));
app.get('/shout', function (req, res) {
res.render('shout', { message: 'hello world' });
});
In your shout.handlebars
:
{{shout message}}
Conclusion
Express-Handlebars is a simple yet powerful templating engine that helps you develop dynamic and reusable components for your Node.js applications. By utilizing its features like partials, helpers, and context-aware templates, you can build well-organized and maintainable codebases.
Implement the above-mentioned APIs and witness the power of server-side rendering with Express-Handlebars.
Hash: 95874802d261a719587d166aca50ec39f1c5ef1ac23753cf1f1aa4eb632bbe7f