'Equivalent of using if .. else as an expression in the Django Template Language

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?



Solution 1:[1]

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 %}">

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 neverwalkaloner
Solution 2