Django的{如果%}标签评价问题,怎么解决

如题所述

{% 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 %}标签多次使用同一个逻辑操作符是没有问题的,但是不能把不同的操作符组合起来。例如,这是合法的:
{% if athlete_list or coach_list or parent_list or teacher_list %}
在执行循环之前先检测列表的大小是一个通常的做法,当列表为空时输出一些特别的提示。
{% if athlete_list %}
{% for athlete in athlete_list %}
<p>{{ athlete.name }}</p>
{% endfor %}
{% else %}
<p>There are no athletes. Only computer programmers.</p>
{% endif %}
因为这种做法十分常见,所以“for”标签支持一个可选的“{% empty %}”分句,通过它可以定义当列表为空时的输出内容,下面的示例与前面的示例等价:
{% for athlete in athlete_list %}
<p>{{ athlete.name }}</p>
{% empty %}
<p>There are no athletes. Only computer programmers.</p>
{% endfor %}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-01-11

第一种方法(使用 {% if %}{% else %}):


第二种方法(使用{% empty %}):

本回答被网友采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网