How to do nested comments in Flask/Jinja?


Like the comments in Hacker News and Reddit. I've looked at Jinja's docs but I can't find anything about recursion (which I assume is how this sort of thing is done). Any ideas?

Thanks in advance.


I already have the data (from an API), and the comments are objects which have children. I just need to know how to render the children recursively in Jinja.

8/8/2011 6:43:26 PM

Accepted Answer

Use macros, they support recursion.

Edit: for loops also support recursion, this would work as well.

8/8/2011 7:07:54 PM

Unless, you give an example how your comment data is laid out, I can only give a basic example how recursive for loops work:

{%- for item in comments recursive %}
    <li>{{ item.text }}</li>
    {%- if item.children -%}
        <ul class="children">{{ loop(item.children) }}</ul>
    {%- endif %}</li>
{%- endfor %}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow