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?

+4  A: 

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

Anders Eurenius
I don't see how this could possibly preserve the hierarchy of the original data unless you render the whole thing to HTML in your view. Can you provide a more concrete example?
Sure. You make a list like [ 'in', 'in', 'blah', 'out', 'blah', 'out'] and then you loop over that in the template. If it's equal to 'in' you emit a li, 'out' you emit a /li and otherwise you just dump the text itself.
Anders Eurenius
+7  A: 

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

+2  A: 

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


Hey John, thanks for your answer. Your link is broken though. The correct link is: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#unordered-list
David Sykes
Works if all you want to output is "<li>sometext</li>" for each item. If you have a nested hierarchy of more complex items, and you (for example) want each item to be a link, then this tag isn't useful.
+3  A: 

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.


direct d/l link: http://jordanovski.com/wp-content/uploads/recurse.zip