DEV Community

Cover image for What is the difference between the extends and include tag in django?
guzmanojero
guzmanojero

Posted on

What is the difference between the extends and include tag in django?

You may want to know the difference between extends and include.

When do you use them?

Let me help you.

1. extends.

  • Purpose: It is used for template inheritance, allowing a child template to build upon a parent template's structure.
  • Usage: A template that uses extends will inherit the content of the specified parent template. The child template can override specific blocks defined in the parent template.
  • Key Concept: Template hierarchy.
  • Common Use Case: Defining a base template (e.g., base.html) with shared layout and style, and then customizing specific sections (like content or title) in child templates.

Parent Template (base.html):

<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
    {% block content %}
    {% endblock %}    
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Child Template (home.html):

{% extends "base.html" %}

{% block content %}
    <h1>Welcome to the Home Page!</h1>
{% endblock %}
Enter fullscreen mode Exit fullscreen mode

2. include

Purpose: It is used to embed one template inside another. The included template's content is rendered directly in place where include is used.
Usage: It does not create a parent-child relationship or support block inheritance; it simply "inserts" the included template's output.
Key Concept: Template inclusion.
Common Use Case: Reusing small, self-contained components like navigation bars, footers, or cards.

Parent Template (base.html):

<!DOCTYPE html>
<html>
<head>
    <title>Website Title</title>
</head>
<body>
    {% include "navbar.html" %}
    <main>
        <h1>Welcome!</h1>
    </main>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Included Template (navbar.html):

<nav>
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/about/">About</a></li>
        <li><a href="/contact/">Contact</a></li>
    </ul>
</nav>
Enter fullscreen mode Exit fullscreen mode

To summarize it:

Feature {% extends %} {% include %}
Purpose Template inheritance Embedding reusable snippets
Relationship Parent-child relationship No relationship
Customizable Blocks Supports {% block %} for overriding No customization; static inclusion
Use Case Structuring templates Reusing smaller components

If we think in terms of OOP terminology, we can say that extends uses inheritance, while include is akin to composition.

Top comments (0)