Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

EDIT:

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.

like image 418
john2x Avatar asked Dec 17 '22 10:12

john2x


2 Answers

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 %}
like image 144
plaes Avatar answered Jan 01 '23 07:01

plaes


Use macros, they support recursion. http://jinja.pocoo.org/docs/templates/#macros

Edit: for loops also support recursion, this would work as well. http://jinja.pocoo.org/docs/templates/#for

like image 35
jd. Avatar answered Jan 01 '23 05:01

jd.