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 Node
s. 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?
Yes, you can do it. It's a little trick, passing the filename to {% include %} as a variable:
correct this:
root_comment.html
tree_comment.html
for example - model:
this might be way more than you need, but there is a django module called 'mptt' - this stores a hierarchical tree structure in an sql database, and includes templates for display in the view code. you might be able to find something useful there.
here's the link : django-mptt
I'm too late.
All of you use so much unnecessary with tags, this is how I do recursive:
In the "main" template:
Then in
menu.html
:I had a similar issue, however I had first implemented the solution using JavaScript, and just afterwards considered how I would have done the same thing in django templates.
I used the serializer utility to turn a list off models into json, and used the json data as a basis for my hierarchy.
Does no one like dicts ? I might be missing something here but it would seem the most natural way to setup menus. Using keys as entries and values as links pop it in a DIV/NAV and away you go !
From your base
call this
It haven't tried the default or the ordered yet perhaps you have ?