Python全系列 教程
3567个小节阅读:5931k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
标签在渲染过程中提供使用逻辑的方法,比如:if和for
标签被 {%
和 %}
包围,如下所示:
由于在模板中,没有办法通过代码缩进判断代码块,所以控制标签都需要有结束的标签
if
判断标签{% if %} {% endif %} :
xxxxxxxxxx
# athlete_list 不为空
{% if athlete_list %}
# 输出 athlete_list 的长度 | 是过滤器
Number of athletes: {{ athlete_list|length }}
{% elif athlete_in_locker_room_list %}
Athletes should be out of the locker room soon!
{% else %}
No athletes.
{% endif %}
firstof
输出不是False的第一个参数,所有参数都为False,则什么都不输出
xxxxxxxxxx
{% firstof var1 var2 var3 %}
等同于
{% if var1 %}
{{ var1 }}
{% elif var2 %}
{{ var2 }}
{% elif var3 %}
{{ var3 }}
{% endif %}
使用默认值:
{% firstof var1 var2 var3 "默认值" %}
逻辑运算符
and、or和not
xxxxxxxxxx
{% if athlete_list and coach_list %}
Both athletes and coaches are available.
{% endif %}
{% if not athlete_list %}
There are no athletes.
{% endif %}
{% if athlete_list or coach_list %}
There are some athletes or some coaches.
{% endif %}
{% if not athlete_list or coach_list %}
There are no athletes or there are some coaches.
{% endif %}
{% if athlete_list and not coach_list %}
There are some athletes and absolutely no coaches.
{% endif %}
允许在同一个标签中使用两个and和or子句, and优先级高于or例如:
xxxxxxxxxx
{% if athlete_list and coach_list or cheerleader_list %}
将被解释为:
if (athlete_list and coach_list) or cheerleader_list
但是在if标签中使用实际的括号是无效的语法。如果你需要它们来表示优先级,你应该使用嵌套if标签
比较运算符
==, !=, <, >, <=, >=, in, not in, is, 和 is not
xxxxxxxxxx
{% if somevar == "x" %}
This appears if variable somevar equals the string "x"
{% endif %}
{% if "bc" in "abcdef" %}
This appears since "bc" is a substring of "abcdef"
{% endif %}
{% if somevar is not True %}
This appears if somevar is not True, or if somevar is not found in the
context.
{% endif %}
优先级,从低到高:
实时效果反馈
1. 关于Django模板,标签if说法正确的是?
A if是通过缩进来表示所属代码块所属
B 需要配合end标签结束标签
C if标签值必须是布尔值
D if可以使用逻辑运算符
答案
1=>D