Eldila
Eldila

Reputation: 15726

Django Template: Comparing Dictionary Length in IF Statement

I am trying to compare the length of a dictionary inside a django template

For example, I would like to know the correct syntax to do the following:

    {% if error_messages %}
        <div class="error">
            {% if length(error_messages) > 1 %}
                Please fix the following errors:
                <div class="erroritem">
                    {% for key, value in error_messages.items %}
                        <br>{{ value }}
                    {% endfor %}
                </div>

            {% else %}
                    {% for key, value in error_messages.items %}
                        {{ value }}
                    {% endfor %}
            {% endif %}
        </div>
    {% endif %}

Upvotes: 3

Views: 14177

Answers (3)

Paolo Bergantino
Paolo Bergantino

Reputation: 488434

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.

Upvotes: 11

gbozee
gbozee

Reputation: 4796

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.

Upvotes: 4

zack
zack

Reputation: 3198

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

Upvotes: 1

Related Questions