Re: Build unordered list in HTML from a python list

Discussion in 'Python' started by Stefan Behnel, Jun 30, 2010.

  1. Nico Grubert, 30.06.2010 10:34:
    > 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},
    > ]
    >
    > From that list I want to create the following HTML code:
    >
    > <ul id="tree">
    > <li>Item 1</li>
    > <li>Item 2</li>
    > <li>Folder 1
    > <ul>
    > <li>Sub Item 1.1</li>
    > <li>Sub Item 1.2</li>
    > </ul>
    > </li>
    > <li>Item 3</li>
    > <li>Folder 2
    > <ul>
    > <li>Sub Item 2.1</li>
    > <li>Folder 2.1
    > <ul>
    > <li>Sub Item 2.1.1</li>
    > <li>Sub Item 2.1.2</li>
    > </ul>
    > </li>
    > </ul>
    > </li>
    > </ul>
    >
    > 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.
    >
    > My problem is: How do I keep track of the closing tags while iterating
    > over the python list?


    Don't. Just use a tool for generating the XML, such as ElementTree's builder.

    http://effbot.org/zone/element-builder.htm
    http://svn.effbot.org/public/stuff/sandbox/elementlib/builder.py

    Stefan
     
    Stefan Behnel, Jun 30, 2010
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Nathan Sokalski
    Replies:
    1
    Views:
    25,969
  2. ibiza
    Replies:
    5
    Views:
    1,185
    S. Justin Gengo [MCP]
    Feb 9, 2006
  3. spaghetti
    Replies:
    3
    Views:
    545
  4. Jukka K. Korpela
    Replies:
    0
    Views:
    800
    Jukka K. Korpela
    Jul 16, 2003
  5. Nico Grubert
    Replies:
    0
    Views:
    299
    Nico Grubert
    Jun 30, 2010
Loading...

Share This Page