Sakeer
Sakeer

Reputation: 2006

How can I Iterate through the same dictionary multiple times in a Django template?

I have a dictionary called categories. And I just want to iterate through this dictionary twice in a Django template. Below is my code:

<div class="first">
  {% for category in categories %}
    <li class="{{category.name}}"><a href="#{{category.name}}">{{category.name}</a></li>
  {% endfor %}
</div>

<div class="lenDict">
   <h2>{{categories|length}}</h2>
</div>

<div class="second">
     {% for category in categories %}
           {% for facet in allFacets %}
                 {% if category.name == facet.category %}
                    <p id="{{facet.id}}">{{facet.facet}}</p>
                 {% endif %}
           {% endfor %}
     {% endfor %}
</div>

When I do it like this the first loop under the div first works fine. But when it comes to the second loop under the div second it gives no result. Also the code under the div lenDict also gives no result.

Are there any limitations in Django templates that we cannot iterate the same dictionary twice? Any help will be appreciated.

Upvotes: 4

Views: 1659

Answers (2)

Menno
Menno

Reputation: 1143

To iterate through an entire dict in Python, you should use .iteritems(). It creates a new iterator over the (key, value) pairs of the dict. You could also use items() if you wanted a list of items instead.

<div class="first">
  {% for key, value in categories.iteritems() %}
    <li class="{{ key }}"><a href="#{{ key }}">{{ value }}</a></li>
  {% endfor %}
</div>

<div class="lenDict">
   <h2>{{ categories|length }}</h2>
</div>

<div class="second">
     {% for key, value in categories.iteritems() %}
           {% for facet in allFacets %}
                 {% if key == facet.category %}
                    <p id="{{facet.id}}">{{facet.facet}}</p>
                 {% endif %}
           {% endfor %}
     {% endfor %}
</div>

Note that your dict will be unordered. If you want to preserve the orders of the keys, use an OrderedDict.

Upvotes: 1

user133688
user133688

Reputation: 7064

So I think this works. I think your issue is facet.category. Is this a fk? because if this is a fk the if statement should be

{% if category.id == facet.category %}

In python iterators don't need to be reset, so I don't think you have to reset your iterators in the tamplate. Note: I would leave this is in a comment but rep isn't high enough.

Upvotes: 0

Related Questions