Search code examples
pythondjangojinja2

How to loop dictionary with multiple values in Jinja?


I have a dictionary like so: {'a': [Object, 0], 'b': [Object, 1] } Where object is an actual object with multiple attributes. I'm trying to a check on each key to see if the second value in the array is a 0 or 1. If it is a 1, then I'll display "Hello" if it's a 0, I'll display "Goodbye" Here's what I have so far that doesn't seem to work:

{% for key in follower_list %}
   {% if follower_list[key][1] == 0 %}
        <p>Hello</p>
   {% else %}
         <p>Goodbye</p>
{% endif %}

Here, follower_list is the dictionary. I'm getting an error by my IDE saying operator expected where follower_list[key][1] is there a way I can do this type of logic in Jinja?


Solution

  • Use iteritems to iterate through your dictionary:

    {% for key, value in follower_list.items %}
        {% if value.1 == 0 %}
            <p>Hello</p>
        {% else %}
            <p>Goodbye</p>
    {% endfor %}
    

    Check this docs.