Frist you have to install jinja2
:
$ pip install Jinja2
Then modify your TEMPLATES
list in the settings.py to contain the jinja2
BACKEND
:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [os.path.join(BASE_DIR, 'templates/jinja2')],
'APP_DIRS': True,
'OPTIONS': {'environment': 'myproject.jinja2.Environment',},
},
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
where templates/jinja2
is the directory with your jinja2 template files.
And in your views.py file:
from __future__ import absolute_import # Python 2 only
from jinja2 import Environment
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse
def environment(**options):
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'url': reverse,
})
return env
This makes static
and url
available in your Jinja2 templates.
P.S. For more details see this article.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…