How to Use the Django include tag in your Templates files.

In this blog post, we are going to take a look at the usage of the {% include %} tag inside Django templates.

What does {% include %} do?

In Django, we use the {% include %} tag, as its name suggests, to include one template within another. This allows you to break down a complex template into smaller, more manageable chunks. The included template inherits the context of the parent template, which means that all of the variables that are available in the parent template will also be available in the included template. This makes it easy to create reusable components that can be included in multiple templates throughout your application; which makes the {% include %} tag a powerful tool for organizing and reusing code in Django templates.

The syntax of the Django template Include tag

The syntax of the Django template {% include %} tag is as follows: We start by enclosing the keyword include by opening and closing Django template sign {% and %}. Then next to the include keyword, we add the string name of the template file we want to include in the current template.

For example, if we want to include a template called navbar.html in another template, we’ll write it like this:

{% include 'navbar.html' %}

How to Use the Django Include Tag

To use the Django include tag, you need to have a parent template and child templates. This parent template file is the one that will link to other child templates using the include tag. Together, these templates will form one single template that gets rendered on a web page all at once.

To illustrate this, we’re going to build a simple layout that contains a navigation bar, a sidebar, the main content, and a footer.

The Problem

Take a look at the template below, it looks small, obviously because we’re using it for learning purposes; But in production sites, the navbar section alone, for example, may be bigger than the whole template altogether. Now imagine if the rest of the sections were also as big as that? All put in a single template. It’ll be a mess of code to even look at.

That’s when the {% include %} tag comes in.

{% load static %}

<!-- base.html -->
<!DOCTYPE html>
<html>
  <head>
    <title>{% block title %}{% endblock %}</title>
  </head>
  <body>
    <!-- Navbar -->
    <header>
      <nav>
        <a href="#">Home</a>
        <a href="#">About</a>
        <a href="#">Contact</a>
      </nav>
    </header>

    <!-- Main content -->
    <main>
      <!-- Sidebar -->
      <aside>
        <ul>
          <li>Link 1</li>
          <li>Link 2</li>
          <li>Link 3</li>
        </ul>
      </aside>

      <!-- Page content -->
      <section>
        {% block content %}{% endblock %}
      </section>
    </main>

    <!-- Footer -->
    <footer>
      <p>Copyright &copy; {{ current_year }}</p>
    </footer>
  </body>
</html>

The above template has 4 sections namely navbar, sidebar, page content, and footer.

The Solution

With the problem we’ve identified above, the solution will be to create 4 more templates, which will be the child templates, each with the code for its corresponding section. Then in the parent template, link the sections to where they belong.

In order to follow along with this tutorial, you have to know how to configure your templates files in a Django project.

Now, let’s take some steps to see the practical use of the {% include %} tag.

Step 1: Creating Child Templates

Since we have a template already, it’s easier to create child templates and then use the remaining template as the parent. It is best to name these child templates with names that resonates to what they do. Like nav.html for a template file that has code for the navigation bar, as we shall see in the next sections. You can also place these files in their own folder if you like.

Creating the nav.html file

Below’s the content for the nav.html file, copied from the navbar section of our original file.

    <!-- Navbar -->
    <header>
      <nav>
        <a href="#">Home</a>
        <a href="#">About</a>
        <a href="#">Contact</a>
      </nav>
    </header>

Creating the sidebar.html file

The content for the sidebar.html file is copied from the sidebar section of our original file.

      <!-- Sidebar -->
      <aside>
        <ul>
          <li>Link 1</li>
          <li>Link 2</li>
          <li>Link 3</li>
        </ul>
      </aside>

Creating the content.html file

Below’s the content for the content.html file, copied from the content section of our original file.

      <!-- Page content -->
      <section>
        {% block content %}{% endblock %}
      </section>

Creating the footer.html file

Next, let’s paste the code for the footer in a template file that we call footer.html

    <!-- Footer -->
    <footer>
      <p>Copyright &copy; {{ current_year }}</p>
    </footer>

Step 2: Updating the Parent Template

Now that our child templates are done, it’s time to modify our parent template. It is best to call the parent template base.html because it is the skeleton of the webpage.

To modify it, we ➊first remove all the code for other components that have their own files and we leave the HTML boilerplate as it is shared with the rest of the child templates. βž‹Where there was code for a component, we use the include tag to link to the template file for that component, like we saw in the syntax section. Your parent template should now look like below:

{% load static %}

<!-- base.html -->
<!DOCTYPE html>
<html>
  <head>
    <title>{% block title %}{% endblock %}</title>
  </head>
  <body>
    <!-- Navbar -->
{% include 'navbar.html' %}

    <!-- Main content -->
    <main>
      <!-- Sidebar -->
{% include 'sidebar.html' %}

      <!-- Page content -->
      <section>
        {% block content %}{% endblock %}
      </section>
    </main>

    <!-- Footer -->
{% include 'footer.html' %}
  </body>
</html>

You can see now that the template is much smaller and manageable.

In the end, your template file structure should look like this:

...
β”œβ”€β”€ templates #here
|   β”œβ”€β”€ base.html
|   β”œβ”€β”€ nav.html
β”‚   β”œβ”€β”€ sidebar.html
|   └── footer.html
└── manage.py

Advanced {% include %} tag Usage

The with Keyword

One of the powerful features of the {% include %} tag is the ability to pass variables to the included template. This can be done using the with keyword. For example, let’s say you have a template called sidebar.html that displays a list of recent blog posts. To pass a variable called “recent_posts” to this template, you would use the following code:

{% include "sidebar.html" with recent_posts=recent_posts %}

In this case, “recent_posts” will be available as a variable in the “sidebar.html” template, and you can use it to display the list of recent blog posts. If you had to pass other data from the models that’s already in the parent template, this will save you from having to create another view.

The {% with %} tag

Adding more to the with keyword, you can also use the {% with %} tag along with the {% include %} tag to create a new variable for use within the included template, without modifying the context of the parent template.

For example, let’s say you have a template called footer.html that displays the current year. To create a variable called “current_year” for use in this template, you would use the following code:

{% with current_year=datetime.now.year %}
    {% include "footer.html" %}
{% endwith %}

The “current_year” variable will be available within the footer.html template, but it will not be accessible in the parent template.

Tips and Tricks when Using {% include%} tag

When using the {% include %} tag in Django templates, it’s important to keep a few best practices in mind:

  • Use template inheritance to build a reusable template structure by using the {% extends %} tag and try to keep your templates as small and focused as possible. This will make it easier to reuse them and make changes in the future.
  • Be careful when passing variables to included templates. Make sure that the variables that you’re passing are actually needed by the included template, and that they won’t cause any naming conflicts.
  • When debugging issues related to template inclusion, make sure to check the TEMPLATES setting in your Django project’s settings.py file. This will ensure that the template you’re trying to include is located in a directory that’s specified in this setting.
  • To optimize the performance of your templates when using the {% include %} tag, you can use the {% load %} tag to load specific template tags. This can help improve the performance of your templates, especially when you have a lot of includes.

And that concludes our blog post. Peace!

Stephen Mclin
Stephen Mclin

Hey, I'm Steve; I write about Python and Django as if I'm teaching myself. CodingGear is sort of like my learning notes, but for all of us. Hope you'll love the content!

Articles: 106