Hi Alan
Here is some test code using recursion I used to create a menu in the
past. I used it in a module but you can test it easily for yourself at the
commandline as I will explain.
def test_html_nodes(nodes,link_to_function='area'):
if not nodes:
nodes = [
{ 'id':1, 'parent_id':0, 'name':'a' },
{ 'id':2, 'parent_id':0, 'name':'b' },
{ 'id':3, 'parent_id':2, 'name':'c' },
{ 'id':4, 'parent_id':2, 'name':'d' },
{ 'id':5, 'parent_id':4, 'name':'e' },
{ 'id':6, 'parent_id':0, 'name':'f' }
]
global output
output = ''
global count
count = 0
def build_node(node):
global output
#output += '<li><a>'+node['name']+'</a>'
li_id = ' id="%s"' % node['id']
output += '<li%s>'%li_id + \
str(A(node['name'],_href=URL(link_to_function,args=[node[
'id']])))
build_nodes(node['id'])
output += '</li>'
def build_nodes(node_parent_id):
global output
global count
count += 1
subnodes = [node for node in nodes if node['parent_id'] ==node_parent_id
]
if len(subnodes) > 0 :
cl = ' class="sf-menu sf-vertical sf-js-enabled sf-shadow"' ifcount
==1 else ''
output += '<ul%s>' % cl
[build_node(subnode) for subnode in subnodes]
output += '</ul>'
build_nodes(0) # Pass in parent id to start as top level nodes
Copy and paste that into a python commandline and then test with:
test_html_nodes(None)
You should see:
<ul class="sf-menu sf-vertical sf-js-enabled sf-shadow">
<li id="1"><a href="/carhire/default/area/1">a</a></li>
<li id="2"><a href="/carhire/default/area/2">b</a>
<ul>
<li id="3"><a href="/carhire/default/area/3">c</a></li>
<li id="4"><a href="/carhire/default/area/4">d</a>
<ul>
<li id="5"><a href="/carhire/default/area/5">e</a></li>
</ul>
</li>
</ul>
</li>
<li id="6"><a href="/carhire/default/area/6">f</a></li>
</ul>
return output