I just finished implementing this. I need a tree structure for sub navigation, but I didn’t want to do anything strange with recursive templates.
The solution I implemented is very simple: I just recursively examine (in my case, a general helper function) and align the hierarchical structure into a simple list. Then in my template, I just use the for loop to iterate through the list.
Each item in the list can be one of three: "in", object, or "out". In my case, I create a series of ul li elements in the view, so when I encounter "in", I create a new ul, when I encounter "out", I close ul. Otherwise, I throw out the item.
My template code is as follows:
{% for item in sub_nav %} {% if item == "in" %} <ul> {% else %} {% if item == "out" %} </ul> </li> {% else %} <li> <a href='{{item.full_url}}'>{{item.name}}</a> {% if item.leaf %} </li> {% endif %} {% endif %} {% endif %} {% endfor %}
The code in the helper function looks like this:
def get_category_nav(request,categories=None): """Recursively build a list of product categories. The resulting list is meant to be iterated over in a view""" if categories==None:
Using these fragments, you should be able to create any hierarchical tree that you want, without any recursion in the template and keeping all the logic in the view.
I know that there was already an accepted answer for this, but I thought that I would send the equipment in case this helps someone else.
source share