Django Include

Reusing templates with the include tag

📦 What is Django Include?

Django include tag allows you to insert one template into another. This promotes code reusability by letting you create reusable template components like headers, footers, and navigation menus across multiple pages.


<!-- Include another template -->
{% include 'header.html' %}
<p>Main content here</p>
{% include 'footer.html' %}
                                    

Include Features

🔄

Basic Include

Insert template into another

{% include 'nav.html' %}
📤

Pass Variables

Send data to included template

{% include 'card.html' 
  with title="Hello" %}
🔒

Isolated Context

Include with only specified vars

{% include 'item.html' 
  with name="Item" only %}
♻️

Reusability

Use same template multiple times

{% include 'button.html' %}

🔹 Basic Include

The simplest form of include inserts a template file into another template. This is perfect for reusing common elements like headers, footers, and navigation across your entire website.

🔸 Header Template (header.html)

<header>
    <h1>My Website</h1>
    <nav>
        <a href="/">Home</a>
        <a href="/about">About</a>
        <a href="/contact">Contact</a>
    </nav>
</header>

🔸 Footer Template (footer.html)

<footer>
    <p>© 2025 My Website. All rights reserved.</p>
</footer>

🔸 Main Template (home.html)

<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
</head>
<body>
    {% include 'header.html' %}
    
    <main>
        <h2>Welcome to Home Page</h2>
        <p>This is the main content.</p>
    </main>
    
    {% include 'footer.html' %}
</body>
</html>

Output:

My Website

Welcome to Home Page

This is the main content.

© 2025 My Website. All rights reserved.

🔹 Include with Variables

Pass specific variables to included templates using the with keyword. This allows you to customize the included template's content while maintaining reusability for different contexts and data.

🔸 Card Template (card.html)

<div class="card">
    <h3>{{ card_title }}</h3>
    <p>{{ card_description }}</p>
    <button>{{ button_text }}</button>
</div>

🔸 Main Template

<div class="cards-container">
    {% include 'card.html' with card_title="Product 1" card_description="Description 1" button_text="Buy Now" %}
    
    {% include 'card.html' with card_title="Product 2" card_description="Description 2" button_text="Learn More" %}
    
    {% include 'card.html' with card_title="Product 3" card_description="Description 3" button_text="View Details" %}
</div>

Output:

Product 1

Description 1

Product 2

Description 2

Product 3

Description 3

🔹 Include with Only

The only keyword restricts the included template to only the variables you explicitly pass. This creates isolated context and prevents unintended variable access for better template encapsulation.

🔸 View

def page(request):
    context = {
        'username': 'Alice',
        'email': '[email protected]',
        'age': 25
    }
    return render(request, 'page.html', context)

🔸 Partial Template (user_info.html)

<div class="user-info">
    <p>Name: {{ username }}</p>
    {# email and age won't be available with 'only' #}
</div>

🔸 Main Template

<h2>User Profile</h2>

{# Include with only specified variable #}
{% include 'user_info.html' with username=username only %}

{# The included template won't have access to email or age #}

Output:

User Profile

Name: Alice

🔹 Include in Loops

Combine include with for loops to render multiple instances of a template with different data. This pattern is powerful for displaying lists of items like products, posts, or user cards.

🔸 View

def products(request):
    context = {
        'products': [
            {'name': 'Laptop', 'price': 999},
            {'name': 'Mouse', 'price': 25},
            {'name': 'Keyboard', 'price': 75}
        ]
    }
    return render(request, 'products.html', context)

🔸 Product Card Template (product_card.html)

<div class="product-card">
    <h4>{{ product.name }}</h4>
    <p>Price: ${{ product.price }}</p>
    <button>Add to Cart</button>
</div>

🔸 Main Template

<h2>Our Products</h2>
<div class="products-grid">
    {% for product in products %}
        {% include 'product_card.html' with product=product %}
    {% endfor %}
</div>

Output:

Our Products

Laptop

Price: $999

Mouse

Price: $25

Keyboard

Price: $75

🔹 Dynamic Include

Use variables to dynamically determine which template to include. This advanced technique allows you to change included templates based on conditions or user preferences at runtime.

🔸 View

def dashboard(request):
    user_type = request.user.user_type  # 'admin' or 'regular'
    context = {
        'sidebar_template': f'{user_type}_sidebar.html'
    }
    return render(request, 'dashboard.html', context)

🔸 Template

<div class="dashboard">
    {# Dynamically include different sidebar based on user type #}
    {% include sidebar_template %}
    
    <main>
        <h2>Dashboard Content</h2>
    </main>
</div>

🔹 Common Use Cases

📌 When to Use Include:

  • Navigation menus - Reuse the same menu across all pages
  • Headers and footers - Consistent site-wide elements
  • Reusable components - Cards, buttons, forms, alerts
  • Sidebar widgets - Social media links, recent posts, ads
  • Form fields - Repeated form elements with different data
  • List items - Product cards, user profiles, blog posts

🔹 Include vs Extends

Understanding when to use include versus extends is important for proper template organization. Both promote reusability but serve different purposes in your template architecture.

🔸 Use Include When:

  • Inserting small, reusable components
  • Same component appears multiple times on one page
  • Component can be used in different contexts

🔸 Use Extends When:

  • Creating a base layout for entire pages
  • Child templates override specific sections
  • Maintaining consistent page structure

💡 Important Tips:

  • Included templates have access to parent template's context by default
  • Use with to pass specific variables to included templates
  • Use only to restrict context to only passed variables
  • Template paths are relative to your templates directory
  • Include is great for DRY (Don't Repeat Yourself) principle
  • Organize reusable templates in a separate folder like includes/

🧠 Test Your Knowledge

What keyword is used to pass variables to an included template?