How can I render a tree structure (recursive) usin

2020-01-27 02:23发布

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?

标签: python django
10条回答
萌系小妹纸
2楼-- · 2020-01-27 02:48

Django has a built in template helper for this exact scenario:

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#unordered-list

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-01-27 02:52

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

查看更多
倾城 Initia
4楼-- · 2020-01-27 02:53

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>
查看更多
够拽才男人
5楼-- · 2020-01-27 02:56

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.

github.com/skid/django-recurse

查看更多
登录 后发表回答