[Django]-Django Templates "for loops" not working correctly

8👍

In Django templates, as in standard Python, using for on a dictionary just loops through the keys. You need to use the .items() method:

{% for key, value in menu.items %}
    <li class="single-link"><a href="{{ value.url }}" title="{{ value.caption }}">{{ value.caption }}</a></li>
{% endfor %}

(Although I realise you’re not actually using the key here, so you could just use for value in menu.values).

Also, note that a dictionary is probably not the right container for your items in any case, as you can’t define the ordering. As armonge suggests, a list is probably better.

1👍

What you need is to have your menu be a list instead of a dictionary

context[‘menu’] = [{‘url’: ‘#’, ‘caption’: ‘test’},{‘url’: ‘#’, ‘caption’: ‘test’}, {‘url’: ‘#’, ‘caption’: ‘test’}]

Leave a comment