ExpressJS: How to pass variables to Pug templates

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

Introduction

ExpressJS, a fast, unopinionated, minimalist web framework for Node.js, provides an efficient way to build server-side applications quickly and effortlessly. One of its strengths is the ability to use templating engines, like Pug (formerly known as Jade), to generate dynamic HTML content. In this tutorial, we’ll dive deep into how you can pass variables from your ExpressJS routes to your Pug templates, bringing your web applications to life.

Understanding Pug Templates

Pug is a high-performance template engine heavily influenced by Haml and implemented with JavaScript for Node.js and browsers. It’s a powerful tool for writing clean, concise HTML. Before we proceed, ensure you’ve got Node.js and ExpressJS installed in your environment. Let’s also install Pug using npm:

npm install pug

Once installed, you can set Pug as your view engine in ExpressJS like this:

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

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

This tells Express to use Pug as its template engine.

Passing Variables to Pug Templates

Passing data from your Express application to Pug templates can be accomplished in several ways. Here we will focus on three primary methods: through the render method, using middleware, and global variables.

Via the Render Method

The most direct way to pass variables to a template is through the render method of the response object in Express. Here’s a simple example:

app.get('/', (req, res) => {
  res.render('index', { title: 'Home Page', message: 'Welcome to Our Website!' });
});

In the above code, 'index' refers to the index.pug file located in your views directory. The second argument to render is an object containing variables (title and message) that will be accessible in the index.pug template.

Using Middleware

Sometimes, you might want to pass variables to all templates globally, such as user information or site configuration. A convenient way to do this is by using middleware. Here’s how you can achieve this:

app.use((req, res, next) => {
  res.locals.siteTitle = 'My Express Site';
  next();
});

res.locals is an object that contains response local variables scoped to the request. Any property added to res.locals can be accessed directly in your Pug templates.

Advanced Techniques

Dynamic Variable Passing

Dynamic data such as query parameters or URL parameters can also be passed to your templates with ease. Here’s an example with URL parameters:

app.get('/user/:name', (req, res) => {
  res.render('user', { name: req.params.name });
});

This route captures a user’s name from the URL and passes it to the user.pug template.

Building Complex Applications

For more complex applications, you might be dealing with arrays and objects. Pug makes it easy to iterate over these structures. Suppose you have an array of user objects and you want to display them:

let users = [
  { name: 'John Doe', email: '[email protected]' },
  { name: 'Jane Doe', email: '[email protected]' }
];

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

In theusers.pug template, you can iterate over this array like so:

ul
  each user in users
    li #{user.name} - #{user.email}

Complex data types and structures can significantly enhance the power of your scopes and allow for more dynamic and interactive web pages.

Conclusion

Passing variables from ExpressJS to Pug templates opens up a world of possibilities for building dynamic, interactive web applications. From basic data passing through route handlers to utilizing middleware for global accessibility, Express and Pug together provide a robust solution for web development. I encourage you to experiment with these techniques, explore the Pug documentation for more advanced usage, and ultimately, harness the full potential of ExpressJS templating.