- 安装jinja2
pip install Jinja2
- 项目下创建文件夹xxx,将jinja2加载到项目
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse
from jinja2 import Environment
def jinja2_Environment(**options):
env = Environment(**options)
env.globals.update(
{
'static':staticfiles_storage.url,
'url':reverse,
}
)
return env
- 设置settings.py,将 ‘jinja2_Environment’ 写进 TEMPLATES
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [os.path.join(BASE_DIR,'index/templates')],
'APP_DIRS': True,
'OPTIONS': {
'environment':'MyDjango.jinjia2Template.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',
],
},
},
]
- 别忘记了设置 STATIC_URL
STATIC_URL = '/static/'