python

Include a template in another template Django

When building a website, there are often common elements that are used on multiple pages. Rather than duplicate code, a template can be created that includes the common elements, and then that template can be included in other templates as needed.

This allows for a DRY (Don't Repeat Yourself) approach to website development and makes maintenance and updates much easier.

In Django, templates can be included in other templates using the {% include %} tag. The included template can be passed variables if needed, and the tag can be used multiple times within a single template.

This can be a very powerful tool when used correctly and can make Django development much more efficient.

home.html

{% include "common/header.html" %}

<div>Main content here</div>

{% include "common/footer.html" %}

In the above code example, The first line includes a header template, the second line has a div element with the main content, and the third line includes a footer template.

The directory structure will look like the below:

> templates
   > common
       header.html
       footer.html
   home.html

In the templates folder, we have created a "common" named folder, and two files - header.html and footer.html in this folder. We are including these files in the home.html template.


In the views.py we can create a home view and use the home.html template in this.

from django.shortcuts import render
  
def home_page(request):
    context = {}
    return render(request, "home.html", context)

Pass data to included template

If you want to pass data to the included template then you can use the below code example:

common > header.html

<div>
   Name is: {{firstname}} {{lastname}}
</div>

And include the above template in the home.html as below:

{% include "header.html" with firstname="John" lastname="Deo" %}

Was this helpful?