【发布时间】:2016-03-02 02:03:13
【问题描述】:
根据Django 1.9 tutorial 上的说明,我在项目根目录中添加了另一个文件,其中包含环境设置 -
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`
(允许加载正确的 jinja2 我必须以不同的方式重命名文件,在本例中为项目根目录中的 jinja2env.py)
我用新的模板后端更新了settings.py:
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',
}
},
在我正在处理的视图中,我使用using 参数来指定jinja2 模板引擎:
return render(request, 'jinja2/index.html', context={'projects': projects, 'counter': 0}, status=200, using='jinja2')
然而,当模板进行渲染时,出现以下错误:'static' is undefined。显然我的设置是错误的,或者我没有做正确的事情。模板开始如下:
<link rel="stylesheet" type="text/css" href="{{ static('stylesheets/main.css') }}">
我做错了什么?我不使用{% load static %},因为它不是 Django 模板……所以我很茫然。
【问题讨论】:
标签: python django templates jinja2