Sling Academy
Home/Node.js/ExpressJS: Conditionally Render Content in Pug Templates

ExpressJS: Conditionally Render Content in Pug Templates

Last updated: February 06, 2024

Introduction to Pug

Pug, formerly known as Jade, is a high-performance template engine heavily influenced by Haml and implemented with JavaScript for Node.js and browsers. It provides a simple and powerful syntax for writing HTML, allowing developers to write cleaner codes. ExpressJS, a backend web application framework for Node.js, makes it easy to integrate Pug templates to serve dynamic content.

Developing dynamic web applications involves sending different content to the client based on certain conditions. A versatile feature of the ExpressJS framework, when used with Pug templates, is its capability to conditionally render content. This tutorial will explore how to implement this to create responsive and interactive web pages without needing to reload or use additional client-side JavaScript.

Environmental Setup

Before we dive in, ensure you’ve the following installed:

  • Node.js
  • ExpressJS
  • Pug

To install ExpressJS and Pug in your project, run:

npm init
npm install express pug --save

Creating Your First Conditional Pug Template

Let’s begin by setting up a basic Express server and render a Pug template.

const express = require('express');
const app = express();

app.set('view engine', 'pug');
app.get('/', (req, res) => {
  res.render('index', { title: 'Home', condition: true });
});

app.listen(3000, () => console.log('Server is running on port 3000'));

In the above example, note how we’ve passed a condition along with the title to the Pug template. Now, let’s see how we can use this condition to conditionally render content.

Basic Conditional Rendering in Pug

Create a file named index.pug in your views directory and add the following content:

doctype html
html
  head
    title #{title}
  body
    if condition
      p Condition is true
    else
      p Condition is false

This Pug template uses an if-else condition to render text based on the condition passed from our Express server.

More Complex Conditions

Conditions in Pug templates can be as complex as necessary. Consider having a user login status to determine the content to display. Adjust your route:

app.get('/dashboard', (req, res) => {
  const loggedIn = // Acquire user's logged-in status
  res.render('dashboard', { loggedIn: loggedIn });
});

Now, in your dashboard’s Pug template:

doctype html
html
  head
    title Dashboard
  body
    if loggedIn
      p Welcome, user!
      a(href='/logout') Logout
    else
      p Please log in.
      a(href='/login') Login

This example demonstrates utilizing conditions based on user state, displaying different elements accordingly.

Using Loops with Conditions

A powerful aspect of Pug templates is the ability to iterate over data structures. Coupling this with conditional logic can produce dynamic lists:

app.get('/users', (req, res) => {
  const users = [{name: 'John', active: true}, {name: 'Jane', active: false}];
  res.render('users', { users: users });
});

And in users.pug:

doctype html
html
  head
    title Users
  body
    ul
      each val in users
        if val.active
          li #{val.name} (Active)
        else
          li #{val.name}

This code iterates over an array of users, applying a conditional check to denote active users specially.

Inline Conditional Expressions

Pug allows for inline expressions, further simplifying the template syntax for conditions. For example:

doctype html
html
  body
    p= 'Welcome, ' + (user ? user.name : 'Guest')

Here, the inline conditional ((user ? user.name : 'Guest') outputs either the user’s name or ‘Guest’ based on the presence of a user object.

Conclusion

In this tutorial, we’ve explored different ways of conditionally rendering content in Pug templates when working with ExpressJS. From basic conditional statements to complex conditions involving loops and inline expressions, Pug and ExpressJS together offer a robust solution for dynamically updating your web pages.

Leveraging these techniques allows developers to create more interactive, user-friendly websites. Remember that keeping your logic in templates simplistic helps maintain readability and manageability of your code.

Next Article: NodeJS: How to include subviews in Pug templates

Previous Article: Node.js: Escape dangerous HTML content in Pug templates

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates