2010-10-30 91 views
0

當有一本字典:嵌套的字典和Django的模板

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

如何將一個疊代,使輸出變爲:

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

目前我使用這一點,但它顯然只是去到一個深度。

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

一種方法是手動重複每個級別的循環,但這樣的解決方案是醜陋的,我希望有一個更乾的。

回答

1

您必須爲此製作自定義模板標籤。我會選擇inclusion tag

{% for k,v in var %} 
{% my_tag v.children %} 
{% endfor %} 
1

如果你已經知道,每個部分都只是將不得不標題&孩子每個,爲什麼不只是做嵌套元組?然後,您可以使用內置過濾器unordered_list

因此,這將會是:

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

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