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.
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 %}
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>
精彩评论