quick example of the setup files to allow the use of Jinja2 template engine within Django, while still being able to import Django template filters (e.g. Humanize).
Following the Django Built-in Template docs, you will need to insure you have Jinja2 installed and then we need to create a jinja2.py
setup file in our main app directory (same locaiton of our settings.py
file).
Navigate to your main app directory and create a file named jinja2.py
Example of project structure with jinja.py
file included:
my_site
├── my_site
│ ├── __init__.py
│ ├── jinja2.py
│ ├── settings.py
│ ├── ...
├── manage.py
├── public
Now we need to setup our Jinja2 environment by populating the jinja2.py
as follows:
from django.templatetags.static import static
from django.urls import reverse
from jinja2 import Environment
def environment(**options):
env = Environment(**options)
env.globals.update({
'static': static,
'url': reverse,
})
return env
To let django know that we have setup a Jinja2 environment and are ready to use it, we need to alter the TEMPLATES.BACKEND
string within settings.py
as follows:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
...
},
]
you can now start using Jinja2 syntax within your templates and django will recognize
While Jinja2 does have a lot of great filters, you may find yourself looking for some of the Django included filters which will not be available in Jinja2 by default.
For example, Humanize is a very useful collection of filters to make dates and numbers easier to read for humans. However, Django requires this filter library be loaded into our template using the {% load humanize %}
tag, which is not supported by Jinja2.
This is where our jinja2.py
environment file really shines by allowing us to import/create filters before the Jinja2 environment is loaded.
In this example we will be using filters form the Django contrib Humanize library; however, you could also define your own filters and import them this way as well.
from django.contrib.humanize.templatetags.humanize import apnumber, intcomma, intword, naturalday, naturaltime, ordinal
Now we add the filters to the Jinja2 environment by adding the following to our jinja2.py
file:
def environment(**options):
...
env.filters.update({
'apnumber': apnumber,
'intcomma': intcomma,
'intword': intword,
'naturalday': naturalday,
'naturaltime': naturaltime,
'ordinal': ordinal,
})
...
Our final jinja2.py
file should look like this
from django.templatetags.static import static
from django.urls import reverse
from django.contrib.humanize.templatetags.humanize import apnumber, intcomma, intword, naturalday, naturaltime, ordinal
from jinja2 import Environment
def environment(**options):
env = Environment(**options)
env.globals.update({
'static': static,
'url': reverse,
})
env.filters.update({
'apnumber': apnumber,
'intcomma': intcomma,
'intword': intword,
'naturalday': naturalday,
'naturaltime': naturaltime,
'ordinal': ordinal,
})
return env