Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Flask (Jinja2) - Template Inheritance

Tech 1

Introduction

Templaet inheritance is a key concept in Jinja2, allowing you to define a base template with common layout and blocks that child templates can override. It promotes code reuse and maintainability.

Code Exapmles

Base Template: base.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>{% block title %}{% endblock %}</title>
</head>
<body>
  <h3><a href="#">Fixed Navigation Bar</a></h3>
{% block content %}
{% endblock %}
<footer style="margin-top: 100px">Fixed Footer</footer>
</body>
</html>

Child Template: child1.html

{% extends "base.html" %}
{% block title %}
Child 1 Title
{% endblock %}

{% block content %}
Child 1 Body Content
{% endblock %}

Child Template: child2.html

{% extends "base.html" %}
{% block title %}
Child 2 Title
{% endblock %}

{% block content %}
Child 2 Body Content
{% endblock %}

Flask Application: app.py

@app.route("/child1")
def child1():
    return render_template("child1.html")

@app.route("/child2")
def child2():
    return render_template("child2.html")

Results

The child templates inherit the base layout and fill in the blocks. The navigation and footer remain the same, while the title and body change.

Result for child1 Result for child2

Practical Use

Template inheritance is useful when you have a consistent layout and want to avoid duplication. It helps in building modular and maintainable web applications.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.