[Django]-Django Template: Comparing Dictionary Length in IF Statement

12👍

You could do this, using the length filter and the ifequal tag:

{% if error_messages %}
    <div class="error">
        {% ifequal error_messages|length 1 %}
            error_messages[0]
        {% else %}
            Please fix the following errors:
            <div class="erroritem">
            {% for key, value in error_messages.items %}
                <br>{{ value }}
            {% endfor %}
            </div>
        {% endifequal %}
    </div>
{% endif %}

Anything else will have to go down the path of custom tags and filters.

4👍

You can actually use both the if tag and the length filter

{% if page_detail.page_content|length > 2 %}
<strong><a class="see-more" href="#" data-prevent-default="">
Learn More</a></strong>{% endif %}

NB
Ensure no spaces between the dictionary/object and the length filter when used in the if tag so as not to throw an exception.

👤gbozee

1👍

use the smart_if template tag:

http://www.djangosnippets.org/snippets/1350/

its super cool 🙂

can do all the obvious stuff like:

{% if articles|length >= 5 %}…{% endif %}

{% if “ifnotequal tag” != “beautiful” %}…{% endif %}

👤zack

Leave a comment