Flask Tutorials: Template Inheritance 🎯

beginner
8 min

Flask Tutorials: Template Inheritance 🎯

Welcome to our in-depth guide on Flask Template Inheritance! This lesson is designed to help you understand how to create reusable and manageable templates in Flask, a popular Python web framework. Let's dive in! 🐘

What is Template Inheritance in Flask? 📝

Template Inheritance allows you to create a base template (often called a parent or supertemplate) that contains common elements shared across multiple web pages. These elements could be the layout, navigation, header, or footer. Child templates (also known as subtemplates) inherit the base template and can override specific sections as needed.

Setting Up a Base Template 💡

Let's create a basic base template called base.html. This template will contain the common layout and navigation elements.

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}Default Title{% endblock %}</title> </head> <body> <nav> <!-- Navigation elements go here --> </nav> <div id="content"> {% block content %} {% endblock %} </div> <footer> <!-- Footer elements go here --> </footer> </body> </html>

In the base template, we have defined two blocks: title and content. Child templates can override these blocks to customize the title and content for each page.

Creating a Child Template 💡

Now, let's create a child template called child.html that inherits from our base template.

html
{% extends "base.html" %} {% block title %} My Child Page {% endblock %} {% block content %} <h1>Welcome to my child page!</h1> <p>This is a child page with custom content.</p> {% endblock %}

In the child template, we use the {% extends %} directive to inherit from our base template. We also override the title and content blocks with our custom content.

Running the Application ✅

To test our templates, let's create a simple Flask application and run it. Here's a basic app.py file:

python
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('child.html') if __name__ == '__main__': app.run(debug=True)

This application will render the child.html template when the root URL (/) is accessed.

Quick Quiz
Question 1 of 1

What is Flask Template Inheritance?

In the next lesson, we'll explore how to pass variables and functions from the parent template to the child template. Until then, happy coding! 🤖