在 Python 中,有两种使用 if
和 else
的方法:用于 bool 流控制,在这种情况下,它与冒号和缩进一起使用,或者作为 https://www.pythoncentral.io/one-line-if-statement-in-python-ternary-conditional-operator/ 中所述的单行表达式。
据我所知,Django 模板语言的 {% if %}
... {% else %}
... {% endif %}
标签等同于前者。但是,我想知道我是否可以以某种方式实现后者来重构下面的代码:
<form action="" method="post">{% csrf_token %}
{% for field in form %}
{% if field.name == "checkin_type" %}
<div class="auto-submit">
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
</div>
{% else %}
<div>
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
</div>
{% endif %}
{% endfor %}
<input type="submit" value="Send message" />
</form>
在这里,我遍历表单的字段并将特定类
"auto-submit"
添加到特定字段 ( <div>
) 的封闭 "checkin_type"
元素。我想按照以下“伪代码”的方式重构它:<form action="" method="post">{% csrf_token %}
{% for field in form %}
<div class="{% if field.name=='checkin_type'%}auto-submit{% else %}{% endif %}">
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
</div>
{% endfor %}
<input type="submit" value="Send message" />
</form>
换句话说,我想通过使用一种三元运算符,仅在
if
的定义中使用 else
... class
语句来减少代码重复。这在 DTL 中可能吗?顺便说一下,如果我尝试使用上面的代码加载模板,我会得到一个
TemplateSyntaxError
:Could not parse the remainder: '=='checkin_type'' from 'field.name=='checkin_type''
也许我只需要正确转义报价?
最佳答案
它应该是 ==
前后的空格,并且您不需要空的 {% else %}
块:
<div class="{% if field.name == 'checkin_type'%}auto-submit{% endif %}">
关于django - 等效于使用 if .. else 作为 Django 模板语言中的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49041089/