How can I render a tree structure (recursive) using a django template?

Tags: django python

I have a tree structure in memory that I would like to render in HTML using a Django template.

class Node():
  name = "node name"
  children = []

There will be some object root that is a Node, and children is a list of Nodes. root will be passed in the content of the template.

I have found this one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.

Does anybody know of a better way?


I had the same problem and I wrote a template tag. I know there are other tags like this out there but I needed to learn to make custom tags anyway :) I think it turned out pretty well.

Read the docstring for usage instructions.

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

{%for node in all_root_elems %} 
    {%include "tree_view_template.html" %}

tree_view_template.html renders the nested ul, li and uses node template variable as below:

<li> {{}}
    {%if node.has_childs %}
         {%for ch in node.all_childs %}
              {%with node=ch template_name="tree_view_template.html" %}
                   {%include template_name%}
By : Rohan

I'm too late) All of you use so much unnecessary with tags, this is how i do recuesive:

in main template:

<!-- lets say that menu_list is already defined -->
    {% include "menu.html" %}

then in menu.html:

{% for menu in menu_list %}
        {{ }}
        {% if menu.submenus|length %}
                {% include "menu.html" with menu_list=menu.submenus %}
        {% endif %}
{% endfor %}

This video can help you solving your question :)
By: admin