Open In App

Template Inheritance: Extend and Block in Pug

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

While creating websites or different web applications, we can first create a base HTML template, and build different pages on top of the base template. This concept of using building pages over a base template is called Template Inheritance. It’s a powerful feature available in web template engines like Pug. We can use template inheritance in Pug using “extend” or “block”.

In this article, we will explore how we can use template inheritance in Pug, along with some examples.

Template Inheritance in Pug

Template inheritance is a method that allows you to create a hierarchy of templates, where child templates inherit structure and functionality from parent templates. This concept creates modular, maintainable, and scalable web applications by separating layout concerns from content specifics.

Extend in Pug

In Pug, the extend keyword is very important for template inheritance. It enables a child template to inherit from a parent template, thereby establishing a relationship between the two. The parent template usually holds the big-picture layout of a webpage, while the child templates deal with specific content.

Block in Pug

It works together with the “extend” keyword. Blocks let child templates change parts of the parent template. This means you can add your own content to certain areas of the parent template, making the website unique without making the code messy.

Template Inheritance using Extend and Block

Step 1: Create a folder name template-inheritance for the project.

mkdir template-inheritance
cd template-inheritance

Step 2: Install pug client to use the pug command.

npm install pug-cli -g

Folder Structure:

wer

Step 3: Create two files named base.pug and home.pug and add the following codes.

HTML
//- base.pug

doctype html
html
  head
    title GFG Article
  body
    header
      h1 Welcome to My Article
    block content
    footer
      p This is a GFG Article
HTML
//- home.pug

extends base.pug

block content
  p This is the home page of GFG Article.

Step 4: Run the below command to get a home.html file and see the output

pug home.pug

Output:

file


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads