Flask / Flask Templates and Jinja2

Template Inheritance

This tutorial dives deeper into the concept of template inheritance in Flask. You'll learn how to create a base template and extend it in child templates, promoting reusability an…

Tutorial 2 of 4 4 resources in this section

Section overview

4 resources

Explains how to use Flask templates and Jinja2 for dynamic content rendering.

Introduction

In this tutorial, we will learn about a key concept in Flask known as Template Inheritance. Template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines blocks that child templates can override.

By the end of this tutorial, you will:
- Understand the concept of template inheritance
- Know how to create a base template in Flask
- Learn how to extend this base template in your child templates

Prerequisites:
- Basic knowledge of Python
- Basic understanding of HTML and CSS
- Familiarity with Flask

Step-by-Step Guide

Template inheritance is a feature in Flask which allows the reusability of HTML code. We can create a base template with common HTML structures (like header, footer, navigation bar, etc.) and then extend this base template on our other templates.

The {% block blockname %} and {% endblock %} statements in Jinja2 are used to denote blocks in your templates that can be overridden by child templates.

Best Practices and Tips

  1. Keep your base template as simple as possible.
  2. Use meaningful names for your blocks to keep things organized.
  3. Try to minimize the use of blocks in your base template.

Code Examples

  1. Creating a base template:

Let's create a base template named base.html.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
    <header>
        {% block header %}Default Header{% endblock %}
    </header>

    <main>
        {% block content %}{% endblock %}
    </main>

    <footer>
        {% block footer %}Default Footer{% endblock %}
    </footer>
</body>
</html>

In the above code, we have defined several blocks (title, header, content, and footer) that can be overridden in our child templates.

  1. Creating a child template:

Now, let's create a child template named home.html that extends base.html.

{% extends "base.html" %}

{% block title %}Home{% endblock %}

{% block header %}
    <h1>Welcome to My Website!</h1>
{% endblock %}

{% block content %}
    <p>This is the home page.</p>
{% endblock %}

{% block footer %}
    <p>Copyright 2022.</p>
{% endblock %}

In this child template, we are overriding all the blocks defined in base.html.

Summary

In this tutorial, we've learned about template inheritance in Flask, created a base template, and extended it in a child template. This concept helps us to avoid code duplication and maintain consistency across our web pages.

For your next steps, try creating more complex base templates and child templates. Practice overriding different blocks and experiment with including default content in your blocks.

Practice Exercises

Exercise 1: Create a base template with a navigation bar and extend this base template in a child template.
Solution:

Base template (base.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
    <nav>
        {% block nav %}
            <a href="/">Home</a> |
            <a href="/about">About</a> |
            <a href="/contact">Contact</a>
        {% endblock %}
    </nav>

    <main>
        {% block content %}{% endblock %}
    </main>
</body>
</html>

Child template (home.html):

{% extends "base.html" %}

{% block title %}Home{% endblock %}

{% block content %}
    <h1>Welcome to the home page!</h1>
{% endblock %}

Exercise 2: Create a child template that only overrides the title block of the base template.
Solution:

Child template (about.html):

{% extends "base.html" %}

{% block title %}About{% endblock %}

In the above code, about.html inherits all content from base.html but overrides the title block.

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

Time Zone Converter

Convert time between different time zones.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

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