How to include a template in another template in Django



Image not found!!

In Django, you can include one template within another using the {% include %} template tag. This allows you to reuse code and keep your templates modular. Here's a basic example:

Let's say you have two templates, base.html and child.html. You want to include child.html within base.html.

base.html

html
<!DOCTYPE html> <html> <head> <title>{% block title %}My Site{% endblock %}</title> </head> <body> <div id="header"> {% block header %} <h1>Welcome to my site</h1> {% endblock %} </div> <div id="content"> {% block content %}{% endblock %} </div> <div id="footer"> {% block footer %} &copy; 2023 My Site {% endblock %} </div> </body> </html>

child.html

html
{% extends 'base.html' %} {% block content %} <p>This is the content of the child template.</p> {% endblock %} {% block footer %} {{ block.super }} Additional content for the child template footer. {% endblock %}

In child.html, we use {% extends 'base.html' %} to indicate that it extends the base.html template. Then, within the blocks (e.g., {% block content %}), you can provide content that will replace the corresponding blocks in the parent template.

Now, when you render child.html, it will include the structure of base.html and override or add content within the specified blocks.

To render these templates in a Django view, you would typically use the render function from django.shortcuts:

python
from django.shortcuts import render def my_view(request): return render(request, 'child.html')

In this example, the child.html template will be rendered, and the content will be included within the base.html structure.