July 3, 2024

ExpressJS: Pug Conditionals

In the post ExpressJS: Pug Template Engine Integration With Examples we have seen how you can use Pug template with Express.js app. In this post we'll see how to use conditional statement in Pug template.

Conditional syntax in Pug template

Using conditional statement, you can execute a block of code based on whether the evaluated condition is true or false.

Pug template has if, else if, else conditional statement.

You can use only if - else

If condition
	…
	…
else
	…
	…

Which can be explained as; if the specified condition evaluates to true execute the if code block. If the specified condition evaluates to false execute the else code block.

You can also have multiple else if blocks if there are more than one condition to be evaluated.

If condition
	…
	…
else if condition
	…
	…
else if condition
	…
	…

else
	…
	…

Express.js - Pug if-else condition example

In the example pug template, we iterate over an array of product objects and display product.name in different colours based on the sales of the products. For that there are conditions based on product.sales.

app.js

const express = require('express');

const app = express();

const port = 3000;
const path = require('path');

// To serve static files like CSS
app.use(express.static(path.join(__dirname, 'public')));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

const products = [{name:'Trousers', sales: 150}, 
    {name:'Sport Shoes', sales: 40},
    {name:'Sneakers', sales: 200},
    {name:'T-Shirts', sales: 70}
]

app.get('/product', (req, res) => {
    res.render('product', {products: products, pageTitle: 'Product Page'});
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

public\css\color.css

Stylesheet for text colours.

.green{
  color: green;
}

.red{
  color: red;
}

.blue{
  color: blue;
}

views\product.pug

doctype html
html(lang="en")
  head
    meta(charset="UTF-8")
    meta(name="viewport", content="width=device-width, initial-scale=1.0")
    title #{pageTitle}
    link(rel="stylesheet", href="/css/color.css")
  body
      h3 Conditional Statement Demo 
      ul
        each product in products
          if product.sales >= 100
            li.green #{product.name}
          else if product.sales < 50
            li.red #{product.name}
          else 
            li.blue #{product.name}

That's all for the topic ExpressJS: Pug Conditionals. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment