模板语法只有两种,变量用 {{ }},标签用{% %}
views.py
class StudentInfo(View): def get(self, request): class Student(object): def __init__(self, name, age): self.name = name self.age = age jack = Student("jack", 18) lucy = Student("lucy", 16) student_list = [jack, lucy] return render(request, "info.html", {"stu": jack, "user": {"name": "zhangsan", "age": 16}, "current_day": datetime.datetime.today(), "text": "python", "items": ["Java", "MySQL", "Oracle"], "numlist": [1, 2, 3, 4, 5], "student_list":student_list, "score": 90})
info.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {# 访问字典值 #} <h2>{{ user.name }}-{{ user.age }}</h2> <hr> {# 访问对象属性 #} <h2>{{ stu.name }}-{{ stu.age }}</h2> <h2>{{ current_day.year }}-{{ current_day.month }}-{{ current_day.day }}</h2> <hr> {# 访问对象的方法 #} <h2>{{ text.upper }}</h2> <hr> {# 访问列表 #} <h2>{{ items.0 }}</h2> <h2>{{ student_list.1.name }}-{{ student_list.1.age }}</h2> <hr> {# 循环取值 #} {% for item in items %} {{ item }} {% endfor %} <hr>
{# 循环取值,倒序 #} {% for num in numlist reversed %} {{ forloop.counter0 }}-{{ num }}<br> {% endfor %} <hr>
{# 循环取值:字典 #} {% for k,v in user.items %} {{ k }},{{ v }} {% endfor %} <hr> {# for empty #} {% for num in numbers %} num {% empty %} 无记录 {% endfor %} <hr> {# if条件判断 #} {% if score >= 90 %} 优秀 {% elif score > 80 %} 良好 {% else %} 要加油了1 {% endif %} </body> </html>