Jinja2 Templates in Django

Django supports 2 different template languages out of the box; Django Template Language (DTL) and Jinja2. The project documentation and most 3rd party tutorials deal exclusively with DTL. There is information on using Jinja2 templates in Django but it is scattered and a bit inconsistent.

This is my attempt to provide a simple introduction to using Jinja2 templates in your Django project. To improve the reach of this document I'll restrict the examples to only use the sample Django project from the official tutorial and to make sure that I use the same terminology as that series of articles.

If you've worked your way through the tutorial and have a working copy of the final code you should have a directory structure that looks like this;

Project folders 1

Enabling Jinja2 templates for the polls application is a 3 step process;

Enable Jinja2 Templates

Add an entry to the TEMPLATES entry in the project settings.py file. This will enable the Jinja2 template parser for your whole project. It should look like this;

TEMPLATES = [  
    {  
        'BACKEND': 'django.template.backends.jinja2.Jinja2',  
        'DIRS': [  
        ],  
        'APP_DIRS': True,  
        'OPTIONS': {  
            "environment": "polls.jinja2.environment",  
        },  
    },
...

Don't remove the section that refers to the DjangoTemplates backend as this will be needed by other applications in your project, particularly the admin application.

Set up Your Jinja2 Environment

Create a jinja2.py file under django_tutorial/polls. This controls which global functions are available to your Jinja2 templates. A simple version will look like this

from jinja2 import Environment  
from django.urls import reverse  
from django.templatetags.static import static


def environment(**options):  
    env = Environment(**options)  
    env.globals.update({  
        "static": static,  
        "url": reverse  
    })  
    return env
Create a Folder for your Jinja2 Templates

By default (and because we set APP_DIRS to True in the Jinja2 template configuration in our settings.py) at run time Django will chose which template backend to use based on the name of the directory any template file is located in. The default for Jinja2 templates is <app name>/jinja2/<app name>. So for our polls application we need a folder called django_tutorial/polls/jinja2/polls.

Project folders 2

Be careful when mixing and matching Jinja2 and Django templates in your own applications though. As a general rule it's better to use one template backend for all of the pages in your application. If you do mix and match make sure that you give each template a distinct name, if only to avoid confusing yourself when you are working on your project.

Note that you can specify your own location for Jinja2 (and Django) templates on a project or application basis but that's beyond the scope of this article.