How can I render a tree structure (recursive) using a django template?
<p>I have a tree structure in memory that I would like to render in HTML using a Django template. </p>

<pre><code>class Node():
  name = "node name"
  children = []
</code></pre>

<p>There will be some object <code>root</code> that is a <code>Node</code>, and <code>children</code> is a list of <code>Node</code>s. <code>root</code> will be passed in the content of the template.</p>

<p>I have found <a href="http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/">this</a> one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.</p>

<p>Does anybody know of a better way?</p>

<p>Using <code>with</code> template tag, I could do tree/recursive list.</p>

<p>Sample code:</p>

<p>main template: assuming 'all_root_elems' is list of one or more root of tree</p>

<pre><code>&lt;ul&gt;
{%for node in all_root_elems %} 
    {%include "tree_view_template.html" %}
{%endfor%}
&lt;/ul&gt;
</code></pre>

<p>tree_view_template.html renders the nested <code>ul</code>, <code>li</code> and uses <code>node</code> template variable as below:</p>

<pre><code>&lt;li&gt; {{node.name}}
    {%if node.has_childs %}
        &lt;ul&gt;
         {%for ch in node.all_childs %}
              {%with node=ch template_name="tree_view_template.html" %}
                   {%include template_name%}
              {%endwith%}
         {%endfor%}
         &lt;/ul&gt;
    {%endif%}
&lt;/li&gt;
</code></pre>
