标签使用 {% %}
注释语句:{# #}
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:
Filter 测试{% for hobby in hobby_list %}
{{ hobby }}
{% endfor %}
运行结果:
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:
Filter 测试{% for hobby in hobby_list %}
{{ hobby }}
{% empty %}
没有东西{% endfor %}
运行结果:
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:
Filter 测试{% if hobby_list|length != 5 %}
列表长度不等于 5
{% else %}
列表长度等于 5
{% endif %}
运行结果:
with 语句:
用来定义一个中间变量,多用于给一个复杂的变量起别名
Filter 测试{% with a=hobby_list.1 %}
{{ a }}
{% endwith %}
{% with hobby_list.0 as b %}
{{ b }}
{% endwith %}
运行结果:
注意:“=” 两边不能加空格