How can I render a tree structure (recursive) using a django template?
Using with
template tag, I could do tree/recursive list.
Sample code:
main template: assuming 'all_root_elems' is list of one or more root of tree
<ul>
{%for node in all_root_elems %}
{%include "tree_view_template.html" %}
{%endfor%}
</ul>
tree_view_template.html renders the nested ul
, li
and uses node
template variable as below:
<li> {{node.name}}
{%if node.has_childs %}
<ul>
{%for ch in node.all_childs %}
{%with node=ch template_name="tree_view_template.html" %}
{%include template_name%}
{%endwith%}
{%endfor%}
</ul>
{%endif%}
</li>
I'm too late.
All of you use so much unnecessary with tags, this is how I do recursive:
In the "main" template:
<!-- lets say that menu_list is already defined -->
<ul>
{% include "menu.html" %}
</ul>
Then in menu.html
:
{% for menu in menu_list %}
<li>
{{ menu.name }}
{% if menu.submenus|length %}
<ul>
{% include "menu.html" with menu_list=menu.submenus %}
</ul>
{% endif %}
</li>
{% endfor %}
I think the canonical answer is: "Don't".
What you should probably do instead is unravel the thing in your view code, so it's just a matter of iterating over (in|de)dents in the template. I think I'd do it by appending indents and dedents to a list while recursing through the tree and then sending that "travelogue" list to the template. (the template would then insert <li>
and </li>
from that list, creating the recursive structure with "understanding" it.)
I'm also pretty sure recursively including template files is really a wrong way to do it...