VOOZH about

URL: https://www.geeksforgeeks.org/node-js/conditionals-in-pug-view-engine/

⇱ Conditionals in Pug View Engine - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Conditionals in Pug View Engine

Last Updated : 23 Jul, 2025

Pug supports JavaScript natively, hence using JavaScript expressions, we can format HTML code. This approach allows us to reuse static web pages which have dynamic data. Angular brackets are not used while specifying the tags.

Conditional Statement in Pug

Conditional statements allow you to execute specific blocks of code based on conditions. If the condition meets then a particular block of statements will be executed otherwise it will execute another block of statement that satisfies that particular condition.

Several methods used to perform Conditional Statements in Pug are:

  • if statement: Executes a code block if a specified condition is true.
  • else statement: Executes a block of code if the same condition of the preceding if statement is false.
  • else if statement: Adds more conditions to the if statement, allowing multiple alternative conditions to be tested.

Syntax

if condition
// pug code
else
// pug code

Syntax for else if

if condition
// pug code
else if condition
//pug code
else
//pug code

Approach to implement Conditionals in Pug View Engine:

  • Express Setup: Initializes an Express.js server.
  • Setting View Engine: Configures Pug as the view engine for rendering templates.
  • Routing: Defines a single route for the root URL (/). When accessed, it renders the Pug template.
  • Pug Template: The Pug template defines the structure and content of the HTML page along with the attributes.
  • Styling: Internal CSS is used within the Pug template (style.) to set margins and styles for headings and other components.

Steps to Install Pug in Node App:

Step 1: Create a NodeJS Application using the following command:

npm init -y

Step 2: Install the required dependencies using the following command:

npm i pug express

Step 3: Create a views folder that contains the pug file.

Folder Structure:

👁 Folder-Structure
Folder Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.18.2",
"pug": "^3.0.2"
}

Example 1: Conditional Statement in Pug

Output:

👁 Conditional-Statement-in-Pug
Conditional Statement in Pug

Example 2: Nested Conditional Statement in Pug

Output:

👁 Nested-Conditional-Statement-in-Pug
Nested Conditional Statement in Pug
Comment

Explore