Reputation: 311
In a .py file I have a function that creates a tree with information (name, type, size etc), given a ziped file. (I want to create a tree view of this ziped file) There is another function that generates <ul>
and <li>
tags for the name of the components, nested if there are children. The function doesn't return anything.
What I want is to have a block in the jinja template displaying the html code from the above function.
The function is:
def print_tree(tree):
print "<ul>"
for t in tree:
print "<li>" + t['name']
if 'children' in t:
print_tree(t['children'])
print "</li>"
print "</ul>"
How can I do this?
Upvotes: 0
Views: 763
Reputation: 1124748
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.
Upvotes: 3