tags:

views:

881

answers:

2

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 %}
+2  A: 

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.

Paolo Bergantino
== 1 isn't the same as > 1 though. Django's template system can be a real pain sometimes...
Deniz Dogan
You would only enter the IF when error_messages is >= 1, so if you ifequal to 1 inside and display the opposite case of what he wanted, the effect is the same.
Paolo Bergantino
Ah, I see what you did now. Horrible to have to go do that though...
Deniz Dogan
Quick question, how do I get the first item in a dictionary. {{ error_messages|first }} doesn't work.
Eldila
Yikes. I'm not really sure, as dictionaries really have no ordering so there's no concept of "first". As ugly as it may be, you could do a {% for .. %} and know that it's only going to execute once because the length of the dictionary is one. Otherwise you'd have to make a custom filter.
Paolo Bergantino
A: 

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