Express.js / Express.js with Template Engines

Rendering Dynamic Views with Pug

This tutorial introduces you to Pug, a template engine for Node.js. We will explore how to use Pug to render dynamic views in an Express.js application.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers using template engines like EJS, Pug, and Handlebars to render dynamic views.

1. Introduction

In this tutorial, we aim to introduce you to Pug, a powerful and robust template engine for Node.js. Pug's syntax is concise, and it helps to render dynamic content in HTML.

By the end of this tutorial, you will learn how to:
- Install and configure Pug in an Express.js application
- Create dynamic views using Pug
- Render these views in your Express.js application

Prerequisites
Before we begin, make sure you have a basic understanding of Node.js and Express.js. Familiarity with HTML and JavaScript is also advantageous.

2. Step-by-Step Guide

Install and Configure Pug

First, create a new Express.js application (you can skip this step if you already have one). Install Express globally if you haven't already:

npm install -g express-generator

Next, create a new Express.js app:

express myapp

Navigate to the new app's directory:

cd myapp

Install the required dependencies:

npm install

To install Pug, run:

npm install pug

In your 'app.js' file, set Pug as your view engine:

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

Creating Pug Templates

In Express.js, views are typically stored in a 'views' folder. To create a Pug file, create a new file with a '.pug' extension.

For example, create 'index.pug' in the 'views' directory:

doctype html
html
  head
    title= title
  body
    h1= message

This will render a simple HTML page with a customizable title and message.

Rendering Views

To render your Pug view, use the 'render' method in your route handler. For example:

app.get('/', function(req, res) {
  res.render('index', { title: 'My App', message: 'Hello there!' });
});

3. Code Examples

Let's expand on the 'index.pug' example:

doctype html
html
  head
    title= title
  body
    h1= message
    ul
      each val in list
        li= val

This will render an HTML page with a title, a message, and a list of items. Here, 'list' is an array that we will pass from our Express.js route.

Our route handler might look like this:

app.get('/', function(req, res) {
  res.render('index', {
    title: 'My App',
    message: 'Hello there!',
    list: ['Apple', 'Banana', 'Cherry']
  });
});

The result will be an HTML page with a list of fruits.

4. Summary

In this tutorial, we've learned how to render dynamic views using Pug in an Express.js application. We've covered installing Pug, creating Pug templates, and rendering these templates from Express routes.

You can further explore Pug's capabilities, like including other Pug files, extending templates, and conditional rendering.

To learn more, visit the official Pug documentation.

5. Practice Exercises

  1. Create a Pug template that displays a user's name and a list of their hobbies. Render this view from an Express route.

  2. Display a list of users where each user has a name and an age. Use conditional rendering in Pug to display a special message for users who are over 50.

  3. Create a Pug layout that includes a header and a footer. Use this layout in multiple views.

Solutions

  1. See the 'index.pug' example above. You can replace 'message' with a user's name and 'list' with a list of their hobbies.

  2. In your Pug template, use the 'each' keyword to loop through users. Within the loop, use an 'if' statement to check if the user's age is over 50. If it is, display your special message.

  3. In Pug, you can create a layout using the 'block' and 'extends' keywords. Create a layout with 'block' placeholders for the header and footer. Then, in your views, use 'extends' to use this layout and fill in the placeholders.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random Number Generator

Generate random numbers between specified ranges.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help