Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 2 of 10 · Django Templates
Interview question

What is template inheritance in Django and how do {% extends %} and {% block %} work? Django में template inheritance क्या है और {% extends %}, {% block %} कैसे काम करते हैं?

Answer

Template inheritance lets a base template define the overall page structure, with child templates overriding specific sections (blocks) - avoiding repeated HTML boilerplate across pages.

# base.html - defines the overall structure
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
    {% block extra_head %}{% endblock %}
</head>
<body>
    <nav>{% include 'navbar.html' %}</nav>
    <main>
        {% block content %}
        <p>Default content</p>
        {% endblock %}
    </main>
    <footer>© 2024</footer>
</body>
</html>

# book_list.html - extends base.html, overrides specific blocks
{% extends 'base.html' %}

{% block title %}Books - My Site{% endblock %}

{% block content %}
<h1>Book List</h1>
<ul>
{% for book in books %}
    <li>{{ book.title }}</li>
{% endfor %}
</ul>
{% endblock %}

# {% extends %} MUST be the first tag in the template
# Any content OUTSIDE a {% block %} in a child template is IGNORED

# Accessing the parent block's content with {{ block.super }}
{% block content %}
{{ block.super }}  <!-- includes whatever was in the parent's block first -->
<p>Additional content specific to this page</p>
{% endblock %}

# Multi-level inheritance is also possible:
# base.html -> app_base.html (extends base.html) -> book_list.html (extends app_base.html)

Template inheritance base template को overall page structure define करने देता है, child templates specific sections (blocks) override करते हैं - repeated HTML boilerplate से बचाता है।

# base.html
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
    <nav>{% include 'navbar.html' %}</nav>
    <main>
        {% block content %}
        <p>Default content</p>
        {% endblock %}
    </main>
    <footer>© 2024</footer>
</body>
</html>

# book_list.html
{% extends 'base.html' %}

{% block title %}Books - My Site{% endblock %}

{% block content %}
<h1>Book List</h1>
<ul>
{% for book in books %}
    <li>{{ book.title }}</li>
{% endfor %}
</ul>
{% endblock %}

# {% extends %} template में सबसे पहला tag होना चाहिए

# Parent block का content {{ block.super }} से access करना
{% block content %}
{{ block.super }}
<p>इस page के लिए extra content</p>
{% endblock %}

Was this answer clear?