Kur*_*eek 4 django django-templates
在 Python 中,有两种使用ifand 的方法else:用于布尔流控制,在这种情况下它与冒号和缩进一起使用,或者作为单行表达式,如https://www.pythoncentral.io/one 中所述-line-if-statement-in-python-ternary-conditional-operator/。
据我所知,Django Template Language 的{% 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>
Run Code Online (Sandbox Code Playgroud)
在这里,我遍历表单的字段并将特定类 , 添加"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>
Run Code Online (Sandbox Code Playgroud)
换句话说,我想通过在定义中使用if...else语句来减少代码重复classonly,通过使用一种三元运算符。这在 DTL 中可能吗?
顺便说一句,如果我尝试使用上面的代码加载模板,我会得到一个TemplateSyntaxError:
无法解析余数:'=='checkin_type'' from 'field.name=='checkin_type''
也许我只需要正确转义报价?
前后应该是空格,并且==不需要空{% else %}块:
<div class="{% if field.name == 'checkin_type'%}auto-submit{% endif %}">
Run Code Online (Sandbox Code Playgroud)
Django 有一个内置的标签过滤器yesno
你可以像这样使用它:
<div class="{{ field.name|yesno:"checkin_type,''" }}">
Run Code Online (Sandbox Code Playgroud)
https://docs.djangoproject.com/en/4.2/ref/templates/builtins/#yesno
| 归档时间: |
|
| 查看次数: |
3284 次 |
| 最近记录: |