django的模板中可以使用逻辑判断吗?


我想在django的模板中做一些逻辑判断,比如

{% if ("view_video" in video_perms) OR purchase_override %}

可以实现吗?

开发 django模板 django

Plics♂C 10 years, 3 months ago

当然可以,具体可以参考 官方文档

这里举几个例子:

{% 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 (OK, so
    writing English translations of boolean logic sounds
    stupid; it's not our fault).
{% endif %}

{% if athlete_list and not coach_list %}
    There are some athletes and absolutely no coaches.
{% endif %}

and和or也可以一起使用,但是, and比or具有更高的优先级,比如:

{% if athlete_list and coach_list or cheerleader_list %}

将被解析为:

if (athlete_list and coach_list) or cheerleader_list
Elims answered 10 years, 3 months ago

Your Answer