Have your function return a string, not print:
def print_tree(tree):
result = ['<ul>']
for t in tree:
result.append("<li>" + t['name'])
if 'children' in t:
result.append(print_tree(t['children']))
result.append("</li>")
result.append("</ul>")
return '\n'.join(result)
You can do the same thing directly in Jinja without a function:
<ul>
{%- for t in tree recursive %}
<li>{{ t.name }}
{%- if t.children -%}
<ul>{{ loop(t.children) }}</ul>
{%- endif %}</li>
{%- endfor %}
</ul>
Here the loop()
call will reuse the for
loop marked recursive
producing a recursive tree structure the same way the print_tree()
function does.