In Python, there are two ways to use if
and else
: either for Boolean flow control, in which case it is used with colons and indentation, or as an expression on a single line as described in https://www.pythoncentral.io/one-line-if-statement-in-python-ternary-conditional-operator/.
As far as I can tell, the Django Template Language's {% if %}
... {% else %}
... {% endif %}
tags are equivalent to the former. However, I was wondering if I could somehow implement the latter to refactor the code below:
<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>
Here I am looping over the fields of the form and adding a particular class, "auto-submit"
, to the enclosing <div>
element of a particular field ("checkin_type"
). I'd like to refactor this along the lines of the following 'pseudocode':
<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>
In other words, I'd like to reduce code repetition by using if
...else
statements in the definition of the class
only, by using a kind of ternary operator. Is this possible in the DTL?
By the way, if I try to load the template with the code above I get a TemplateSyntaxError
:
Could not parse the remainder: '=='checkin_type'' from 'field.name=='checkin_type''
Perhaps I just need to do the quote escaping correctly?
It should be spaces before and after ==
and you don't need empty {% else %}
block:
<div class="{% if field.name == 'checkin_type'%}auto-submit{% endif %}">
Django has a built-in tag filter yesno
You can use it like so:
<div class="{{ field.name|yesno:"checkin_type,''" }}">
https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#yesno
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With