django - 等效于使用 if .. else 作为 Django 模板语言中的表达式

标签 django django-templates

在 Python 中,有两种使用 ifelse 的方法:用于 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/

相关文章:

django - 如何修复错误 : pg_config executable not found on Elastic Beanstalk permanently

django - 使用 Django 的 unique_together 避免重复的数据库索引

python - 在 Python 和 Django 中从 Javascript 解码 unicode

django - 使用django将数据保存到数据库

database - 没有数据库的django模型

django - 检查列表 django 模板中的存在

python - Django 文本标记编辑器

python - 有谁知道用于 snmp 监控的基于 python 的 Web ui 吗?

python - django render_to_response 如何发送特殊字符

Django内联表单集添加另一个并删除