Sling Academy
Home/Node.js/NodeJS + Pug: How to create reusable layouts (header, footer)

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

Last updated: February 06, 2024

Overview

When building web applications, maintaining a consistent look and feel across your pages is essential. Using NodeJS together with Pug (formerly known as Jade), a high-performance template engine, can significantly simplify the creation of reusable layouts, such as headers and footers. In this tutorial, we’ll explore how to leverage these powerful technologies to build modular, maintainable web applications.

Setting Up Your Environment

Firstly, ensure you have NodeJS installed on your computer. You can download it from nodejs.org. Next, you’ll need to set up a new NodeJS project. Open your terminal or command prompt, navigate to your project directory, and initialize your project:

mkdir myproject
cd myproject
npm init -y
npm install express pug

This command creates a new directory for your project, initializes a new npm project within it, and installs Express and Pug, which are essential for this tutorial.

Creating Your First Pug Layout

Pug templates are based on indentation to define the document structure. Let’s create a basic layout that includes a header and footer that can be reused across different pages.

Create a views directory in your project folder and inside, create a file named layout.pug:

doctype html
html
  head
    title Your Website
  body
    header
      h1 Your Website Header
    block content
    footer
      p Copyright © 2023 Your Website

The block content directive is where the unique content of each page will be inserted. This layout acts as a skeletal structure for your pages.

Creating a Page Using the Layout

Next, let’s create a home page that uses this layout. In the views directory, create a file named home.pug:

extends layout.pug

block content
  section
    p Welcome to our website!

By using extends layout.pug, we’re telling Pug to use layout.pug as the base layout for home.pug. The content within the block content will replace the content of the block content in the layout.

Setting Up an Express Server

To display your Pug templates, you’ll need a web server. Express is a fast, unopinionated, minimalist web framework for Node.js that works well with Pug. Let’s set one up:

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

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

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

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

This code sets Pug as the view engine, tells Express where to find the Pug templates, creates a route for the home page, and starts a server listening on port 3000.

Implementing Reusable Components

Headers and footers often contain navigation menus, branding, and copyright information that should be consistent across pages. To avoid duplicity and maintain a single source of truth, you can use Pug’s include directive to separate these elements into their own files.

Create two files in your views directory: header.pug and footer.pug. In header.pug, you might have:

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

And in footer.pug, something like:

footer
  p Copyright © 2023 Your Website

Then, in layout.pug, replace the existing header and footer tags with:

include header.pug
block content
include footer.pug

This modular approach allows you to maintain a consistent structure across your web application while enabling flexibility in the content of individual pages.

Adding Static Files

Express can serve static files, such as CSS, JavaScript, and images. Create a public directory in your project folder. Inside, you can add subdirectories for stylesheets, scripts, and images. To serve these files, add the following line to your express app:

app.use(express.static('public'));

Conclusion

Using NodeJS and Pug to create reusable layouts like headers and footers streamlines the development process, allowing you to maintain a coherent structure throughout your web application. By breaking down the UI into modular components, you can easily update and reuse them, improving maintainability and scalability. With this knowledge, you’re well on your way to building dynamic, efficient web applications.

Previous Article: NodeJS: How to include subviews in Pug templates

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