views:

36

answers:

2

When there is a dictionary:

menu = {'title': 'Link1',
        'children': {'title': 'Child of Link1',
                     'children': #etc..}
        }

How would one iterate over it so that the output becomes:

<ul>
    <li>Link1
    <ul>
        <li>Child of Link 1
            <ul>
               <li>Grandchild of Link 1
               <ul>etc..</ul>
               </li>
             </ul>
         </li>
     </ul>
     </li>
</ul>

Currently I use this, but it obviously only goes to a depth of one.

    <ul id="mainnavigation">     
    {% for k,v in admin.items %} #ContextProcessor, because this menu needs to know the current path.
            <li class="expandable"><a href="{{ v.path }}">{{ v.title }}</a>
                {% if v.children != None %}
                    <ul>
                    {% for id,child in v.children.items %}
                            <li class="expandable"><a href="{{ child.path }}">{{ child.title }}</a></li>
                    {% endfor %}
                    </ul>
                {% endif %}
            </li>
    {% endfor %}
</ul>

One way would be to manually repeat the loop for each level, however such a solution is ugly and I am hoping there is a more DRY one.

+1  A: 

You'll have to make custom template tag for this. I would choose inclusion tag.

{% for k,v in var %}
{% my_tag v.children %}
{% endfor %}
Anpher
+1  A: 

If you already know that every part is just going to have title & children for each, why not just do nested tuples? You can then just use the built in filter, unordered_list.

So, it'd be:

menu = (Link 1 (Child of Link 1 (Grandchild of Link 1 (...) )))

and

<ul id="mainnavigation">
  {{ menu|unordered_list }}
</ul>
desfido