Build unordered list in HTML from a python list
Remi Carton
remi.carton at amadeus.com
Wed Jun 30 08:12:23 EDT 2010
> Dear list members
>
> I have this python list that represets a sitemap:
>
> tree = [{'indent': 1, 'title':'Item 1', 'hassubfolder':False},
> {'indent': 1, 'title':'Item 2', 'hassubfolder':False},
> {'indent': 1, 'title':'Folder 1', 'hassubfolder':True},
> {'indent': 2, 'title':'Sub Item 1.1', 'hassubfolder':False},
> {'indent': 2, 'title':'Sub Item 1.2', 'hassubfolder':False},
> {'indent': 1, 'title':'Item 3', 'hassubfolder':False},
> {'indent': 1, 'title':'Folder 2', 'hassubfolder':True},
> {'indent': 2, 'title':'Sub Item 2.1', 'hassubfolder':False},
> {'indent': 2, 'title':'Folder 2.1', 'hassubfolder':True},
> {'indent': 3, 'title':'Sub Item 2.1.1', 'hassubfolder':False},
> {'indent': 3, 'title':'Sub Item 2.1.2', 'hassubfolder':False},
>
> If an item of the list has 'True' for the 'hassubfolder' key than a new
> "<ul><li>" must be created instead of "</li>" after its title. (See
> "Folder 2" node in the HTML code above.
Or you can change your list to a dict with a tree structure and use
recursion instead of a stack:
tree = [
{ 'title': 'Item 1', 'children': [] },
{ 'title': 'Item 2', 'children': [] },
{ 'title': 'Folder 1', 'children': [
{ 'title':
'sub item 1.1',
'children' : [],
},
{ 'title':
'Folder 1.1',
'children' : [ .. ],
},
] },
]
and something like:
def displayListItem(i):
print '<li>%s' % i['title']
if i['children']:
print '<ul>'
for c in i['children']:
displayListItem(c)
print '</ul>'
print </li>
you might also use recursion with your existing list, by 'pop'ing the
first item and passing the rest of the list.
Remi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100630/78238ec6/attachment-0001.html>
More information about the Python-list
mailing list