Sling Academy
Home/Node.js/ExpressJS: How to pass variables to Pug templates

ExpressJS: How to pass variables to Pug templates

Last updated: February 06, 2024

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.

Next Article: ExpressJS: Conditionally Render Content in Pug Templates

Previous Article: Using ExpressJS and Multer with TypeScript

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