ExpressJS + Pug: How to use loops to render array data

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

Introduction

In the world of web development, rendering data dynamically is a common challenge. Especially, when working with server-side technologies like ExpressJS in combination with templating engines such as Pug (formerly Jade), it becomes crucial to master how to loop through data structures like arrays to display content on the web pages smoothly. This guide will walk you through the process of using loops in Pug templates to render array data, served by an ExpressJS application.

Setting Up the Environment

Before diving into the code, ensure that you have Node.js installed on your machine. This will also install npm (Node Package Manager), which is essential for managing your project dependencies. Once you’ve confirmed the installation, initiate a new Node.js project by navigating to your project directory and running:

npm init -y

This command generates a package.json file that will manage your project’s dependencies.

Installing Express and Pug

With your project setup, the next step involves installing Express and Pug. Run the following command:

npm install express pug

This will add both Express and Pug to your package.json, marking them as dependencies for your project.

Creating an Express Application

Start by creating a file named app.js. This will be the entry point of your Express application. Open it and add the following boilerplate Express setup:

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

app.set('view engine', 'pug');
app.set('views', './views');

app.get('/', (req, res) => {
  res.render('index');
});

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

In the above code, we start by importing the Express library. We then create an app instance, set the ‘view engine’ to use Pug, and define where our views will be stored with ‘views’. We define a route that renders a view called ‘index’ when visiting the root URL.

Creating Pug Templates

To use Pug for rendering your views, create a directory named views in the root of your project. Inside, create a file named index.pug. For simplicity, let’s start with a basic Pug template:

doctype html
html
  head
    title Express + Pug Demo
  body
    h1 Data Rendering with Pug!

This template sets up a basic HTML structure with a heading. It’s now ready to display dynamic content.

Rendering Array Data with Loops in Pug

Let’s say you want to display a list of users. First, modify your app.js route to pass an array of user names to the Pug template:

app.get('/', (req, res) => {
  const users = ['Alice', 'Bob', 'Charlie'];
  res.render('index', { users });
});

Then, in your index.pug file, you can loop through the users array and display each user’s name within an HTML list:

doctype html
html
  head
    title Express + Pug Demo
  body
    h1 Data Rendering with Pug!
    ul
      each user in users
        li= user

This Pug syntax (each user in users) iterates over the users array, and for each element, it creates a list item (li) displaying the user’s name.

Rendering Complex Data Structures

Arrays containing objects are common in web applications. Imagine having an array of objects, where each object represents a user with a name and age. You can render this data similarly:

app.get('/', (req, res) => {
  const users = [
    { name: 'Alice', age: 30 },
    { name: 'Bob', age: 24 },
    { name: 'Charlie', age: 29 }
  ];
  res.render('index', { users });
});

In your index.pug file, update the list to also display the age of each user:

doctype html
html
  head
    title Express + Pug Demo
  body
    h1 Data Rendering with Pug!
    ul
      each user in users
        li #{user.name} - Age: #{user.age}

Here, the syntax #{user.name} and Age: #{user.age} interpolates the name and age values from each object in the users array into the list items.

Conclusion

By now, you should have a basic understanding of how to use ExpressJS and Pug to render dynamic data, particularly array data, on your web pages. From simple lists to more complex data structures, the combination of ExpressJS and Pug’s powerful templating capabilities allows you to craft dynamic web experiences with ease. Keep experimenting with these tools, and you’ll discover even more ways to improve your web applications.