Per the instructions on the Django 1.9 tutorial I've added another file in the project root with the Environment settings -
from __future__ import absolute_import # Python 2 only
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from jinja2 import Environment
def environment(**options):
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'url': reverse,
})
return env`
(Granted to load the proper jinja2
I had to rename the file something differently, in this case jinja2env.py
in project root)
And I updated settings.py
with the new templating backend:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(PROJECT_ROOT, 'templates').replace('\\','/')],
'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',
],
},
},
{
'BACKEND': "django.template.backends.jinja2.Jinja2",
'DIRS': [os.path.join(PROJECT_PATH, 'campaigns/templates').replace('\\','/')],
"APP_DIRS": True,
"OPTIONS": {
'environment': 'jinja2env.Environment',
}
},
In the view I'm working on I use the using
parameter to specify the jinja2
templating engine:
return render(request, 'jinja2/index.html', context={'projects': projects, 'counter': 0}, status=200, using='jinja2')
Yet when the template goes to render I have following error: 'static' is undefined
. Clearly my setup is wrong or I am not doing something correct. The template starts as such:
<link rel="stylesheet" type="text/css" href="{{ static('stylesheets/main.css') }}">
What am I doing wrong? I don't use {% load static %}
since it isn't a Django template ... so I'm at a loss.
You're loading the wrong environment. In your code jinja2env.Environment
actually refers to default Environment from jinja2.Environment
.
"OPTIONS": {
'environment': 'jinja2env.Environment',
}
should be changed to
"OPTIONS": {
'environment': 'jinja2env.environment',
}
Notice the lowercase environment
, which is the environment you defined inside jinja2env.py
.
根据您的设置和对该问题的可接受答案,您似乎应该尝试添加static
上下文处理器。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.