Sling Academy
Home/Node.js/NodeJS: How to include subviews in Pug templates

NodeJS: How to include subviews in Pug templates

Last updated: February 06, 2024

Introduction

Pug is a high-performance template engine heavily influenced by Haml and implemented with JavaScript for Node.js and browsers. It facilitates writing cleaner and more readable HTML. Its primary features include a simple syntax, code reusability, and the ability to include files, which makes organizing bigger projects much more manageable.

When developing web applications with Node.js and Pug (formerly known as Jade), structuring your views intelligently can greatly enhance the readability, maintainability, and modularity of your project. Pug templates offer an elegant syntax for HTML, and with the ability to include subviews, developers can create reusable and nested components effortlessly. This tutorial will walk you through including subviews in your Pug templates within a Node.js environment.

Setting Up Your Project

First, ensure that you have Node.js installed on your machine. Then, create a new directory for your project and initialize a new Node.js project:

mkdir my-pug-project
cd my-pug-project
npm init -y

Install Express and Pug:

npm install express pug

Next, create an ‘app.js’ file and set up a basic Express server:

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

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

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

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

In the root of your project, create a folder named ‘views’. Inside this folder, you will store all your Pug template files. Let’s start with an ‘index.pug’ file:

doctype html
html
  head
    title My Pug Project
  body
    h1 Welcome to my Pug project!

Including Subviews

Including subviews is a powerful feature in Pug that allows you to include the content of one Pug file within another. This promotes reusability and keeps your templates organized. Let’s see it in action.

1. Creating a Subview

Create a new Pug file named ‘header.pug’ inside the ‘views’ directory and add the following code:

header
  nav
    ul
      li: a(href='/') Home
      li: a(href='/about') About Us

This code represents a reusable navigation header that we want to include in our ‘index.pug’ layout.

2. Including the Subview in a Parent View

To include the ‘header.pug’ file inside ‘index.pug’, simply use the ‘include’ directive:

// in index.pug
include header

Now, when you navigate to ‘/’, you’ll see the header displayed on the page. The ‘include’ directive tells Pug to take the content of ‘header.pug’ and insert it into ‘index.pug’ at the location of the include statement.

Reusing Subviews with Parameters

Pug also allows passing parameters to subviews, enabling even more powerful reusability. Let’s demonstrate this by creating a footer that accepts a year parameter.

1. Creating a Parameterized Subview

Create a new file named ‘footer.pug’ within your ‘views’ folder:

footer
  p Copyright © #{year}

In this example, #{year} is a placeholder for a variable passed from the parent view.

2. Including the Subview with Parameters

To pass a parameter to a subview, you must include it as follows:

// in some parent view
- var year = new Date().getFullYear()
include footer

By declaring a variable ‘year’ above the include statement and accessing it inside ‘footer.pug’, you dynamically pass the current year into the footer subview.

Conclusion

In conclusion, Pug’s include feature is incredibly powerful for organizing your Node.js project’s frontend components. By breaking your UI into reusable subviews and intelligently including them where necessary, you can streamline your development process and build more maintainable applications. Adding dynamic data through parameters, utilizing mixins for reusable blocks and extends for inheritance, takes your Pug templating to the next level, making your code cleaner and more efficient.

Next Article: NodeJS + Pug: How to create reusable layouts (header, footer)

Previous Article: NodeJS: Using express-fileupload to simply upload files

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