Jinja2's “recursive” modifier and django-mptt

I recently found myself staring at django-mptt’s template tags, thinking about how I could use recursetree inside of a Jinja2 template. django-mptt’s template tags are (totally reasonably) tied to Django’s own templating language, which means they aren’t immediately compatible with Jinja2. C’est la vie.

As I was about to port this to a Jinja2 template function, I wondered to myself: can Jinja2's {for…in} loop control structure do this for me?

It can!

Here’s how: {for…in} comes with a recursive modifier. When recursive is used, the loop variable can be called inside of itself with an iterable of child records from the node presently being handled. In practice, the template code looks like this:

So, if my django-mptt-backed tree has the structure

then the code above would render the tree as

And now I don’t need to fuss with rendering trees outside of my template. That’s pretty cool.

To anyone not already using Jinja2 with Django, absolutely make the switch if you can. We use jingo at Pitchfork, a lovely no-frills drop-in.