ExpressJS: How to render JSON in Pug templates

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

Introduction

When developing web applications using ExpressJS, rendering views can be a pivotal task for sending information to the client side. Pug, formerly known as Jade, stands out as one of the preferred template engines for Express due to its simplicity and powerful features. This tutorial aims to dive deep into the nuances of rendering JSON data in Pug templates, which can be a common scenario when dealing with APIs or dynamic content. We’ll explore everything from setting up your Express application to passing JSON data into your Pug templates, and manipulating this data for display.

Setting Up Your Express App

Before diving into rendering JSON data, you must have an Express application setup. If you’re new to this, follow the steps below to create a simple Express application:

  1. Initiate a new Node.js project by running npm init in your terminal.
  2. Install Express by executing npm install express.
  3. Add Pug to your project with npm install pug.
  4. Create an app.js file and require the necessary modules:
const express = require('express');
const app = express();

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

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

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

Understanding JSON data

JSON (JavaScript Object Notation) is a lightweight data-interchange format that’s easy to read and write for humans and easy to parse and generate for machines. JSON is composed of key-value pairs and ordered lists of values. It is used commonly by APIs for data transfer across the web.

Passing JSON Data to Pug Templates

Now that your Express app is up and running, let’s focus on rendering JSON data. The process involves passing the data from your Express routes to your Pug templates.

Consider you have the following JSON data:

{
  "user": {
    "name": "Alex",
    "age": 30,
    "interests": ["coding", "biking", "hiking"]
  }
}

To pass this data to your Pug template, modify the root route in your app.js:

app.get('/', (req, res) => {
  res.render('index', { user: {
    name: "Alex",
    age: 30,
    interests: ["coding", "biking", "hiking"]
  } });
});

In your index.pug file, you can now access and manipulate this data:

doctype html
html
  head
    title= title
  body
    h1 Hello #{user.name}
    p Age: #{user.age}
    ul
      each interest in user.interests
        li= interest

Manipulating JSON Data in Pug Templates

One of the great features of Pug is the ability to use JavaScript directly within your templates. This means you can iterate over arrays, work with objects, and utilize control statements right within your Pug file. The example above shows a simple iteration over the user’s interests.

For more complex manipulations, Pug’s syntax remains straightforward and efficient. Consider the following JSON data representing a list of users:

{
  "users": [
    {"name": "Alex", "age": 30},
    {"name": "Jamie", "age": 25},
    {"name": "Sam", "age": 35}
  ]
}

To display each user and their respective age, you might write your Pug template like this:

doctype html
html
  head
    title= title
  body
    h2 List of Users
    ul#users
      each user in users
        li 
          h3= user.name
          p Age: #{user.age}

This method not only allows for simple data rendering but also complex data manipulation within your templates. Not to mention, it enhances your web application’s dynamism by featuring live data that might constantly evolve over time.

Conclusion

Rendering JSON data in Pug templates via ExpressJS opens a myriad of possibilities for your web application. From simple data display tasks to complex manipulations and dynamic content representation, understanding these principles is crucial. The ease of passing JSON data from Express routes to Pug templates and the flexibility in manipulating data using Pug’s powerful syntax empowers developers to create richer, more interactive web applications. Remember, the detailed examples provided in this tutorial are just the beginning. Experiment, learn from doing, and consult the extensive documentation of both Express and Pug to expand your capabilities further.