python - django if 语句中的括号

标签 python django templates django-templates django-views

如何在 Django 模板中干净利落地执行此操作?基本上如果 A, or (B and C) ,我想展示一些 HTML。

我基本上有这个:

{% if user.is_admin or something.enable_thing and user.can_do_the_thing %}

现在,这有点模棱两可。我试过做

{% if user.is_admin or (something.enable_thing and user.can_do_thething) %}

但是你不能使用括号。文档说要使用嵌套的 ifs(或者在这种情况下是 elifs,我猜,它是一个 OR),但我不想在 2 个 if block 中重复相同的 HTML,这听起来很可怕。

最佳答案

正如 Mihai Zamfir 所说,它应该可以按预期工作。正如 Django 文档所述:

允许在同一标签中同时使用 andor 子句,and 具有 更高 优先级比例如:

{% if player_list 和 coach_list 或啦啦队长 %}

将被解释为:

if (athlete_list 和 coach_list) 或啦啦队列表

https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#boolean-operators

关于python - django if 语句中的括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27486913/

相关文章:

python - python `str()`函数是否调用类的 `__str__()`函数?

python - 将 Django QuerySet 格式化为以数组形式输出值

c++ - 为什么在这里通过引用传递指针会导致错误?

python - ValueError:层激活_1调用的输入不是符号张量

Python 链接拉取器

Django 简单搜索表单

python - 在 Django 中按月分组并检索为 datetime.date()

c++ - 功能模板的默认参数不起作用

c++ - 非模板类的模板化构造

python - 关闭极坐标 matplotlib 图的轴边界