Dan*_*hal 16 django logic templates boolean django-templates
我不确定这是否真的很简单,我只是在文档中浏览它,或者如果这是Django模板系统的限制,但我需要能够在Django中做一些(不是非常)高级逻辑而且我宁愿不必重复自己.
假设我有3个布尔值; A,B和C.
我基本上需要这样做:
{% if A and (B or C) %}
{{ do stuff }}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
但是,Django似乎不允许(B or C)用括号对逻辑进行分组.有没有办法在Django的模板语言中进行这种分组?或者我需要做那个的非DRY版本,这将是:
{% if A and B %}
{{ do stuff }}
{% else %}
{% if A and C %}
{{ do the same stuff }}
{% endif %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
Pet*_*per 27
在if标记中使用实际括号是无效的语法.如果需要它们来指示优先级,则应使用嵌套的if标记.
这是使用嵌套标记表达逻辑的更简洁方法:
{% if A %}
{% if B or C %}
{{ do stuff }}
{% endif %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
将括号内的任何内容分配给变量.
{% with B or C as D %}
{% if A and D %}
{{ do stuff }}
{% endif %}
{% endwith %}
Run Code Online (Sandbox Code Playgroud)
PS:这不适用于较新的版本.
| 归档时间: |
|
| 查看次数: |
10247 次 |
| 最近记录: |