Python的Django框架中if标签的相关使用

yipeiwu_com5年前Python基础

{% if %} 标签检查(evaluate)一个变量,如果这个变量为真(即,变量存在,非空,不是布尔值假),系统会显示在 {% if %} 和 {% endif %} 之间的任何内容,例如:

{% if today_is_weekend %}
  <p>Welcome to the weekend!</p>
{% endif %}

{% else %} 标签是可选的:

{% if today_is_weekend %}
  <p>Welcome to the weekend!</p>
{% else %}
  <p>Get back to work.</p>
{% endif %}

Python 的“真值”

在Python和Django模板系统中,以下这些对象相当于布尔值的False

  •     空列表([] )
  •     空元组(() )
  •     空字典({} )
  •     空字符串('' )
  •     零值(0 )
  •     特殊对象None
  •     对象False(很明显)

    提示:你也可以在自定义的对象里定义他们的布尔值属性(这个是python的高级用法)。

除以上几点以外的所有东西都视为`` True``

{% if %} 标签接受 and , or 或者 not 关键字来对多个变量做判断 ,或者对变量取反( not ),例如: 例如:

{% 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 %}

{% if %} 标签不允许在同一个标签中同时使用 and 和 or ,因为逻辑上可能模糊的,例如,如下示例是错误的: 比如这样的代码是不合法的:

{% if athlete_list and coach_list or cheerleader_list %}

系统不支持用圆括号来组合比较操作。 如果你确实需要用到圆括号来组合表达你的逻辑式,考虑将它移到模板之外处理,然后以模板变量的形式传入结果吧。 或者,仅仅用嵌套的{% if %}标签替换吧,就像这样:

{% if athlete_list %}
  {% if coach_list or cheerleader_list %}
    We have athletes, and either coaches or cheerleaders!
  {% endif %}
{% endif %}

多次使用同一个逻辑操作符是没有问题的,但是我们不能把不同的操作符组合起来。 例如,这是合法的:

{% if athlete_list or coach_list or parent_list or teacher_list %}

并没有 {% elif %} 标签, 请使用嵌套的`` {% if %}`` 标签来达成同样的效果:

{% if athlete_list %}
  <p>Here are the athletes: {{ athlete_list }}.</p>
{% else %}
  <p>No athletes are available.</p>
  {% if coach_list %}
    <p>Here are the coaches: {{ coach_list }}.</p>
  {% endif %}
{% endif %}

一定要用 {% endif %} 关闭每一个 {% if %} 标签。

相关文章

Python跑循环时内存泄露的解决方法

Python跑循环时内存泄露的解决方法

Python跑循环时内存泄露 今天在用Tensorflow跑回归做测试时,仅仅需要循环四千多次 (补充说一句,我在个人PC上跑的)。运行以后,我就吃饭去了。等我回来后,Console窗口...

使用Python的Django框架实现事务交易管理的教程

 如果你花费了很多的时间去进行Django数据库事务处理的话,你将会了解到这是让人晕头转向的。 在过去,只是提供了简单的基础文档,要想清楚知道它是怎么使用的,还必须要通过创建和...

Python对文件和目录进行操作的方法(file对象/os/os.path/shutil 模块)

使用Python过程中,经常需要对文件和目录进行操作。所有file类/os/os.path/shutil模块时每个Python程序员必须学习的。 下面通过两段code来对其进行学习。 1...

python通过文件头判断文件类型

对于提供上传的服务器,需要对上传的文件进行过滤。 本文为大家提供了python通过文件头判断文件类型的方法,避免不必要的麻烦。 分享代码如下 import struct # 支...

对python中使用requests模块参数编码的不同处理方法

对python中使用requests模块参数编码的不同处理方法

python中使用requests模块http请求时,发现中文参数不会自动的URL编码,并且没有找到类似urllib (python3)模块中urllib.parse.quote("中文...