I’m trying to build template tags that take use a dictionary in settings.py to build a menu.
I have this as part of my template.
{% for menu_item in menu %}
<li class="single-link"><a href="{{ menu_item.url }}" title="{{ menu_item.caption }}">{{ menu_item.caption }}</a></li>
{% endfor %}
The context passed to this tag contain
context['menu'] = {'keywords': {'url': '#', 'caption': 'test'}, 'start': {'url': '#', 'caption': 'test'}, 'flippa': {'url': '#', 'caption': 'test'}}
{{ menu.start.caption }} works fine, however within my for loop, menu_item just contains just 'keywords' or 'start' or 'flippa' and using . doesn’t work at all.
Anyone know what I am doing wrong here?
Disclaimer: I’ve only been using django and python for a week!
In Django templates, as in standard Python, using
foron a dictionary just loops through the keys. You need to use the.items()method:(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.