In Pug, "includes" are a way to modularize and reuse code by importing separate Pug files into a main Pug file. This helps in organizing code more efficiently and reduces duplication of code by allowing you to include common sections or components across multiple pages easily. In simple words, Includes allows you to insert the contents of one Pug file into another.
How Do Includes Work in Pug?
The syntax for including a file in Pug is straightforward. You use the include
keyword followed by the path to the file you want to include. Pug then processes these files during compilation and includes their content in the main file.
include filename_withpath
Prerequisites
Steps to Setup Pug Template Engine
Step 1: Create a Node.js application using the following command:
npm init
Step 2: Install required Dependencies
npm i pug express
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.18.2",
"pug": "^3.0.2"
}
Example: This example demonstrate the use of Include keyword.
// views/index.pug
html
head
// Set the title of the HTML page
title Pug Include Example
// Internal CSS styles for the page
style.
h1 {
color: green;
}
body
// Including header.pug file in a page
include header.pug
// Display the main heading of the page
h1 GeeksForGeeks | Include Example
// Including footer.pug file in a page
include footer.pug
//views/header.pug
p this is included header
hr
//views/footer.pug
hr
p this is included footer
// index.js
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
// Set Pug as the view engine
app.set('view engine', 'pug');
// Set the views directory to 'views' in the current directory
app.set('views', path.join(__dirname, 'views'));
// Define a route to render
// the Pug template when the root path is accessed
app.get('/', (req, res) => {
// Render the Pug template named 'index'
res.render('index');
});
// Start the server and listen on the specified port
app.listen(port, () => {
// Display a message when the server starts successfully
console.log(`Server is running at http://localhost:${port}`);
});
Step 4: To run the application use the following command
node index.js
Output: Now go to http://localhost:3000 in your browser:
Benefits of Using Includes in Pug
- Modularity: Includes encourage modular coding practices by breaking down complex templates into smaller, manageable parts.
- Reusability: Code reusability is promoted as you can include common components like headers, footers, or navigation menus across multiple pages.
- Maintainability: Updates or changes to included files automatically reflect in all files where they are included, reducing maintenance efforts and potential errors.
- Organization: Includes help in organizing code by separating concerns and improving the overall structure of your project.