jinja2介绍
Jinja2:是 Python 下⼀个被⼴泛应⽤的模板引擎,是由Python实现的模板语⾔,他的设计思想来源于 Django 的模板引擎,并扩展了其语法和⼀系列强⼤的功能,尤其是Flask框架内置的模板语⾔
由于django默认模板引擎功能不⻬全,速度慢,所以我们也可以在Django中使⽤jinja2, jinja2宣称⽐django默认模板引擎快10-20倍。
Django主流的第三⽅APP基本上也都同时⽀持Django默认模板及jinja2,所以要⽤jinja2也不会有多少障碍。
配置文件
2-1:在主项目目录(里面有asgi.py)下面创建jinja2_env.py
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse
from jinja2 import Environment
def environment(**options):
env = Environment(**options)
env.globals.update({ # 修改
'static': staticfiles_storage.url, # 模板出现static,调用url函数
'url': reverse # 模板出现url,调用reverse函数
})
return env # 返回修改后的环境变量
2-2:编辑主目录 __init__.py 文件
from .jinjia2_env import environment
如果没有引用会引发如下错误
KeyError: 'jinja2'
During handling of the above exception, another exception occurred:
AttributeError: module 'mysite' has no attribute 'environment'
The above exception was the direct cause of the following exception:
raise ImportError(
ImportError: Module "qsboxcn" does not define a "environment" attribute/class
Win32 exception occurred releasing IUnknown at 0x00000171C16E7A10
Win32 exception occurred releasing IUnknown at 0x000001FF71A37F60
2-3:在相同目录配置settings.py文件
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [os.path.join(BASE_DIR, 'test/templates')],
#这里是应用的路劲
'APP_DIRS': True,
'OPTIONS': {
'environment': 'mysite.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',
],
},
},
]
尽情使用吧
3.1 编辑应用下面的 views.py文件
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
request_data = {
"user":"admin"
}
# return HttpResponse(f"Hello Jinhe!")
return render(request, "index.html", context=request_data)
# return render(request, "settings.html", context=request_data)
3.2编辑 template目录下面的 index.html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>清爽盒子</title>
</head>
<body style="color:gray;font-size:16px;background-color:black;">
{% if user != "AnonymousUser" %}
<h3>欢迎您! {{ user }} </h3>
{% else %}
<h3>欢迎您访问,请登录! </h3>
{% endif %}
</body>
</html>
3.3:响应结果展示登录前后的