1、配置
在⼯程中创建模板⽬录templates。
在settings.py配置⽂件中修改TEMPLATES配置项的DIRS值:
TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [os.path.join(BASE_DIR,'templates')],'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',],},},]
2、定义模板
在templates⽬录中新建⼀个模板⽂件,如index.html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><body><h1>{{ color }}</h1></body></html>
3.模板渲染
调⽤模板分为两步骤:
找到模板 loader.get_template(模板⽂件在模板⽬录中的相对路径) -> 返回模板对象
渲染模板 模板对象.render(context=None, request=None) -> 返回渲染后的html⽂本字符串,context 为模板变量字典,默认值为None request 为请求对象,默认值为None
定义视图:方法一
class UserView(View):def get(self,request):#获取template对象t=loader.get_template('film/index.html')#Template().render()==>strreturn HttpResponse(t.render({'color':'yellow'}))
方法2
class UserView(View):def get(self,request):data={'color':'red'}return render(request,'film/index.html',data)
4.模板语法
4.1 模板变量
变量名必须由字⺟、数字、下划线(不能以下划线开头)和点组成。
语法如下:
模板变量可以使python的内建类型,也可以是对象。
路由
urlpatterns = [path('register/',views.UserView.as_view()),]
视图类:
class UserView(View):def post(self,request):content={'color': '红⾊','filmdict': {'fname': 'hello我的家⼈', 'people': '⻩渤'},'fidlist': [1001, 1002, 1003, 1004, 1005],'pub_date': datetime.strptime('-10-30', '%Y-%m-%d').date()}return render(request,'film/index.html',content)
模板内容
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><body><h1>{{ color }}</h1><h1>{{ filmdict }}</h1><h1>{{ filmdict.fname }}</h1><h1>{{ fidlist }}</h1><h1>{{ fidlist.1 }}</h1><h1>{{ pub_date }}</h1><h1>{{ pub_date.year }}</h1></body></html>
响应结果:
4.2 模板语句
1)for循环:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><body><ul>{% for key,value in filmdict.items %}<li>{{ forloop.counter }}--{{ key }}---{{ value }}</li>{% endfor %}</ul></body></html>
响应结果:
2)for…empty
for 标签带有⼀个可选的{% empty %} 从句,以便在给出的组是空的或者没有被找到时,进⾏操作。
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><body>{% for person in person_list %}<p>{{ person.name }}</p>{% empty %}<p>sorry,no person.name</p>{% endfor %}</body></html>
3)if判断
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><body>{% if age >= 60 and age < 80 %}<P>及格</P>{% elif age > 80 and age < 95 %}<P>良好</P>{% else %}<P>优秀</P>{% endif %}</body></html>
4)⾃动转义标签 autoescape
⾃动转义:将HTML⾃动转换成普通字符串输出。不进⾏标签解析。
{% autoescape off %} Hello {{ name }}{% endautoescape %}<hr>{% autoescape on %} Hello {{ name }}{% endautoescape %}
响应结果
更多详细的模板语法参考:/en/2.2/ref/templates/builtins/