I'm using the nested set hierarchy, or modified preorder tree traversal (MPTT) algorithm, as described here, and I'm having a difficult time understanding how to translate the depth and category name into a Chameleon template to display a nested tree using <ul>
and <li>
.
I have a dict
that has both depth and category name information for all the categories that looks like:
[{'depth': 1L, 'name': 'CategoryA'}, {'depth': 2L, 'name': 'CategoryB', ...]
Adapting this source, the way to print this information in Python is:
category_ul = ""
current_depth = -1
category_list.pop(0)
while category_list:
current_node = category_list.pop(0)
category_name = current_node['name']
category_depth = current_node['depth']
if category_depth > current_depth:
category_ul += "<ul>\n"
if category_depth < current_depth:
category_ul += "</ul>\n" * (current_depth - category_depth)
category_ul += "<li>%s</li>\n" % str(category_name)
current_depth = category_depth
if not category_list:
category_ul += "</ul>\n" * (current_depth + 1)
What I'd like to do is translate this Python code to something that can be used in a Chameleon template using tal
.
The closest answer I have seen is Rendering nested elements with an arbitrary depth using Chameleon ZPT, but it requires children nodes for each node, which doesn't seem to be the right solution.
So, my question is: How can I implement the Python code above in a Chameleon template? I'd really appreciate any help I can get. So far, I have tried:
<tal:block tal:define="current_depth -1">
<tal:block tal:repeat="category categories_list">
<ul tal:condition="python:category['depth'] > current_depth">${category['name']}</ul>
<tal:block tal:define:"current_depth category['depth']"></tal:block>
<span>current_depth: ${current_depth}</span>
</tal:block>
</tal:block>
But, current_depth
is always defined as -1. If it isn't obvious from the template code above, I'm pretty new to it, so any help would be greatly appreciated! Thanks.