相当于使用if .. else作为Django模板语言中的表达式

问题描述 投票:1回答:1

在Python中,有两种方法可以使用ifelse:或者用于布尔流控制,在这种情况下它用于冒号和缩进,或者作为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

无法解析余数:'=='checkin_type''来自'field.name =='checkin_type''

也许我只需要正确地逃避报价?

django django-templates
1个回答
4
投票

它应该是==之前和之后的空格,你不需要空的{% else %}块:

<div class="{% if field.name == 'checkin_type'%}auto-submit{% endif %}">
© www.soinside.com 2019 - 2024. All rights reserved.