Introduction to Express Layouts
Express Layouts is a powerful middleware for Node.js web applications using Express.js. It allows developers to create templated views and layouts easily. Enhance your web application’s structure and maintainability by utilizing express-layouts to manage the layout of your web pages effectively.
Setting Up Express Layouts
npm install express express-ejs-layouts
Basic Usage
After installing express-layouts, you need to set up your Express app to use it:
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const app = express();
app.set('view engine', 'ejs');
app.use(expressLayouts);
app.get('/', (req, res) => {
res.render('index');
});
app.listen(3000, () => {
console.log('App is running on port 3000');
});
Creating Layouts
Create a file named layout.ejs
in the views
directory:
My Application
<%- body %>
Using Layouts
Now, create another EJS view file, for instance, index.ejs
:
Welcome to My Application
This is the home page.
Defining Sections
With express-layouts, you can define sections in your layouts:
My Application
<%- include('partials/header') %>
<%- body %>
Including Partials
Partials are a great way to include reusable sections of your layout:
Header Content
Customizing Layouts per Route
You can also customize layouts on a per-route basis:
app.get('/about', (req, res) => {
res.render('about', { layout: 'custom-layout' });
});
Example Application
Here is a complete example of an Express.js application utilizing express-layouts:
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const app = express();
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(expressLayouts);
// Middleware for logging requests
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
// Routes
app.get('/', (req, res) => {
res.render('index', { title: 'Home Page' });
});
app.get('/about', (req, res) => {
res.render('about', { title: 'About Us', layout: 'custom-layout' });
});
app.get('/contact', (req, res) => {
res.render('contact', { title: 'Contact Us' });
});
app.listen(3000, () => {
console.log('App is running on port 3000');
});
By following these steps, you can effectively manage and organize your web application’s layout using express-layouts, making your code cleaner and easier to maintain. Start leveraging the power of Express Layouts today!
Hash: 5796917351d35868bc075dbda0ac44c2a283d3aad7526e01765e36f25a2fa57a