简体   繁体   中英

Django Templates “for loops” not working correctly

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 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.

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'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM