Subjects

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

What is the difference between {% include %} and {% extends %} in Django templates? Django templates में {% include %} और {% extends %} में क्या अंतर है?

Answer
TagPurposeRelationship
{% extends %}Inherit a parent template's structure, override blocksChild-parent (one template extends another)
{% include %}Insert another template's content directly at that pointComposition (embedding a reusable fragment)
# navbar.html - a reusable fragment
<nav>
    <a href='/'>Home</a>
    <a href='/books/'>Books</a>
    {% if user.is_authenticated %}
        <a href='/logout/'>Logout</a>
    {% endif %}
</nav>

# base.html uses include to embed the fragment
<body>
    {% include 'navbar.html' %}
    {% block content %}{% endblock %}
</body>

# Passing extra context to an included template
{% include 'book_card.html' with book=featured_book highlight=True %}

# only=True limits the included template to ONLY the passed variables,
# not the full surrounding context
{% include 'book_card.html' with book=featured_book only %}

# A template can use BOTH extends and include together
# page.html
{% extends 'base.html' %}
{% block content %}
    {% include 'book_card.html' with book=book %}
{% endblock %}

# KEY DIFFERENCE: extends is about INHERITING a page's overall layout
# (one per template, must be the first tag); include is about REUSING
# a fragment (can be used multiple times, anywhere in the template)
Tagउद्देश्यRelationship
{% extends %}Parent template inherit करना, blocks override करनाChild-parent
{% include %}दूसरे template का content directly insert करनाComposition
# navbar.html
<nav>
    <a href='/'>Home</a>
    <a href='/books/'>Books</a>
</nav>

# base.html include use करता है
<body>
    {% include 'navbar.html' %}
    {% block content %}{% endblock %}
</body>

# Included template को extra context देना
{% include 'book_card.html' with book=featured_book highlight=True %}

# only=True सिर्फ passed variables तक सीमित करता है
{% include 'book_card.html' with book=featured_book only %}

# extends और include साथ भी use हो सकते हैं
# page.html
{% extends 'base.html' %}
{% block content %}
    {% include 'book_card.html' with book=book %}
{% endblock %}

Was this answer clear?