Open In App

What is includes in Pug View Engine ?

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:

Screenshot-2024-03-19-121957

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:

pug-include

Benefits of Using Includes in Pug

Article Tags :