前言
模板语法,本质上是在 HTML 中写一些占位符,由数据对这些占位符进行替换和处理。
正文
1、创建一个新的模板页面
-
编辑urls.py
from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ # path('admin/', admin.site.urls), # www.xxx.com/index/ -> 函数 path("tpl/", views.tpl), ]
-
编辑views.py
from django.shortcuts import render, HttpResponse # Create your views here. # 需要有默认参数request def tpl(request): name = "Jack" return render(request, "tpl.html",{"n1":name})
-
在templates下新建tpl.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>模板语法</h1> </body> </html>
2、模板语法介绍
如果说我们从数据库中取到了数据,如何在 html 页面中进行展示呢,这里需要用到 templates 的基本语法
2.1 单一变量
-
修改views.py
def tpl(request): name = "Jack" return render(request, "tpl.html",{"n1":name})
-
修改templates下的tpl.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>模板语法</h1> <div>{{n1}}</div> </body> </html>
2.2 列表
-
修改views.py
def tpl(request): name = "Jack" roles = ["CEO", "CFO", "CTO"] return render(request, "tpl.html", {"n1": name, "n2": roles})
-
修改templates下的tpl.html
<body> <h1>模板语法</h1> <div>{{n1}}</div> <div>{{n2}}</div> <div>{{n2.0}}</div> <div>{{n2.1}}</div> <div>{{n2.2}}</div> </body>
2.3 列表(循环)
-
修改templates下的tpl.html
<div> {% for item in n2 %} <span>{{item}}</span> {% endfor %} </div>
2.4 字典
-
修改views.py
def tpl(request): name = "Jack" roles = ["CEO", "CFO", "CTO"] user_info = {"name": "Mack", "age": 25, "role": "CTO"} return render(request, "tpl.html", {"n1": name, "n2": roles, "user_info": user_info})
-
修改templates下的tpl.html
<div> {{ user_info }} {{ user_info.name }} {{ user_info.age }} {{ user_info.role }} </div>
2.5 字典(循环)
- 修改templates下的tpl.html
<div> <div> {% for k,v in user_info.items %} {{ k }} = {{ v }} {% endfor %} </div> </div>
2.6 列表套字典
-
修改views.py
def tpl(request): name = "Jack" roles = ["CEO", "CFO", "CTO"] user_info = {"name": "Mack", "age": 25, "role": "CTO"} date_list = [ {"name": "LiLei", "age": "25", "role": "CIO"}, {"name": "HanMeimei", "age": "18", "role": "CEO"}, {"name": "QinChao", "age": "22", "role": "CFO"} ] return render(request, "tpl.html", {"n1": name, "n2": roles, "user_info": user_info, "date_list": date_list})
-
修改templates下的tpl.html
<hr/> <div> {% for item in date_list %} <div>{{ item.name }} {{ item.age }} {{ item.role }}</div> {% endfor %} </div> <hr/>
2.7 条件语句
- 修改templates下的tpl.html
<hr/> {% if n1 == "Jack" %} <h1>条件正确</h1> {% else %} <h1>条件错误</h1> {% endif %} <hr/>