Jinja2 is a powerful templating engine for Python. In the context of Django, it’s used as a part of Django’s templating system to render dynamic content within HTML files. Django itself has its default templating engine, but developers can integrate Jinja2 into Django projects for those who prefer its syntax and features.
Now, let’s explore how to include other templates using Jinja2 in a Django application. In Django, we can include other templates within our base template using the {% include %}
tag. This inclusion can be useful for components that appear across multiple pages, such as headers, footers, or navigation menus.
The syntax of the {% include %}
tag is as follows:
{% include template_name %}
Here’s a coding example of the {% include %}
tag with Jinja2 in Django:
Bud1 ge.pyIl manage.pyIlocblob�.������my_appIlocblob.������my_appbwspblob�bplist00� ]ShowStatusBar[ShowPathbar[ShowToolbar[ShowTabView_ContainerShowSidebar\WindowBounds[ShowSidebar _{{259, 342}, {920, 436}} %1=I`myz{|}~��my_appvSrnlong my_projectIlocblob�.������ my_projectbwspblob�bplist00� ]ShowStatusBar[ShowPathbar[ShowToolbar[ShowTabView_ContainerShowSidebar\WindowBounds[ShowSidebar _{{259, 342}, {920, 436}} %1=I`myz{|}~�� my_projectvSrnlong @� @� @� @E DSDB `� @� @� @
/my_project/my_app/templates/my_app
contains the following django templates:
base.html
file serves as the foundational template for our web application. It typically contains the basic structure shared across multiple pages, such as the HTML structure, header, footer, and other common elements. In this file, Django’s {{% include %%}}
tag is used include three other templates:
header.html
main.html
footer.html
/my_project/my_app/views.py
contains the index
function, which handles requests to the index page of our application:
django.shortcuts
, which is used to render templates.base.html
template. We pass three additional context variables along with the request:
header
: This context variable points to the /my_project/my_app/templates/my_app/header.html
template.main
: This context variable points to the /my_project/my_app/templates/my_app/main.html
template.footer
: This context variable points to the /my_project/my_app/templates/my_app/footer.html
template.Note: These context variables are crucial for dynamically including the header, main content, and footer within the
base.html
template.
base.html
template and the provided context.In a nutshell, the {% include %}
tag in Django allows us to modularize our templates and reuse components across multiple pages, promoting code reuse and maintainability in our web applications.
Free Resources