ExpressJS: Conditionally Render Content in Pug Templates

Updated: February 6, 2024 By: Guest Contributor Post a comment

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.