【问题标题】:Parentheses in django if statementdjango if 语句中的括号
【发布时间】:2015-02-13 17:14:24
【问题描述】:

如何在 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 块中重复相同的 HTML,这听起来很可怕。

【问题讨论】:

  • 不加括号。我认为它有效;)
  • 您不想在if 块中使用嵌套的 if 和括号,因此显然框架不支持您所要求的解决它并将您的复杂逻辑移动到模板标签或视图。

标签: python django templates django-templates django-views


【解决方案1】:

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

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

{% if athlete_list and coach_list or cheerleader_list %}

将被解释为:

if (athlete_list and coach_list) or cheerleader_list

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

【讨论】:

  • 能否提供官方文档的链接?有用的答案
  • 倒转:{% if athlete_list and coach_list or athlete_list and cheerleader_list %} 等于 if athlete_list and (coach_list or cheerleader_list)
【解决方案2】:

您可以在视图中进行检查并将标志传递给上下文。

show_html = user.is_admin or (something.enable_thing and user.can_do_the_thing)
context['show_html'] = show_html

然后在你的模板中你可以检查标志

{% if show_html %}

【讨论】:

  • 我不会将此逻辑放入视图中,而是使用自定义标签
  • 如果这些变量之一需要是循环迭代变量怎么办? django 对此感到失望。
猜你喜欢
  • 1970-01-01
  • 2014-11-11
  • 2017-06-14
  • 2019-12-14
  • 2012-05-03
  • 1970-01-01
  • 2012-07-02
相关资源
最近更新 更多