标签使用 {% %}
注释语句:{# #}
for 循环:
views.py:
from django.shortcuts import render, redirect, HttpResponse from app01 import models # Filter 测试 def filter_test(request): hobby = ["Reading", "Basketball", "Movie", "Music"] return render(request, "filter_test.html", {"hobby_list": hobby,})
filter_test.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Filter 测试</title> </head> <body> {% for hobby in hobby_list %} {{ hobby }} {% endfor %} </body> </html>
运行结果:
for 循环的其它使用方式:
forloop.counter | 当前循环的索引值,从 1 开始 |
forloop.counter0 | 当前循环的索引值,从 0 开始 |
forloop.revcounter | 当前循环的倒序索引值,从 1 开始 |
forloop.revcounter0 | 当前循环的倒序索引值,从 0 开始 |
forloop.first | 当前循环是不是第一次循环,结果为布尔值 |
forloop.last | 当前循环是不是最后一次循环,结果为布尔值 |
forloop.parentloop | 本层循环的外层循环 |
empty:
如果内容为空的话,就执行,配合 for 循环使用
views.py:
from django.shortcuts import render, redirect, HttpResponse from app01 import models # Filter 测试 def filter_test(request): hobby = [] return render(request, "filter_test.html", {"hobby_list": hobby,})
filter_test.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Filter 测试</title> </head> <body> {% for hobby in hobby_list %} {{ hobby }} {% empty %} <li>没有东西</li> {% endfor %} </body> </html>
运行结果:
if 语句:
if 语句支持 ==、>、<、!=、<=、>=、and、or、in、not in、is、is not 判断
views.py:
from django.shortcuts import render, redirect, HttpResponse from app01 import models # Filter 测试 def filter_test(request): hobby = ["Reading", "Basketball", "Movie", "Music"] return render(request, "filter_test.html", {"hobby_list": hobby,})
filter_test.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Filter 测试</title> </head> <body> {% if hobby_list|length != 5 %} <p>列表长度不等于 5</p> {% else %} <p>列表长度等于 5</p> {% endif %} </body> </html>
运行结果:
with 语句:
用来定义一个中间变量,多用于给一个复杂的变量起别名
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Filter 测试</title> </head> <body> {% with a=hobby_list.1 %} {{ a }} {% endwith %} <!-- 或者 --> {% with hobby_list.0 as b %} {{ b }} {% endwith %} </body> </html>
运行结果:
注意:“=” 两边不能加空格