4

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.

john2x
  • 22,546
  • 16
  • 57
  • 95
  • what's the question exactly? if you're wondering about how jinja works, why not just having a look at its source code? – mdeous Aug 08 '11 at 17:45
  • @john2x - are you asking how to store data about replies to comments in your backend (and if so, what are you using) or are you asking about how to render such comments in HTML and CSS (and are you looking for suggestions about generating such HTML with Jinja2)? – Sean Vieira Aug 08 '11 at 18:01
  • I already have the data (from an API), and the comments are objects which have children comments, so on so forth. I just need to know how to render the children recursively in Jinja. – john2x Aug 08 '11 at 18:44
  • Can you show the structure of your comments object? – plaes Aug 08 '11 at 19:10

2 Answers2

7

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 %}
plaes
  • 31,788
  • 11
  • 91
  • 89
  • any additipn to this answer. especially if no `item.children` implementation but `item.parent` only. – binrebin Sep 17 '20 at 12:37
5

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

jd.
  • 10,678
  • 3
  • 46
  • 55