Build unordered list in HTML from a python list

Jorgen Grahn grahn+nntp at snipabacken.se
Wed Jun 30 10:28:57 EDT 2010


On Wed, 2010-06-30, Kushal Kumaran wrote:
> On Wed, Jun 30, 2010 at 2:04 PM, Nico Grubert <nicogrubert at yahoo.de> wrote:
>> 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},
>>       ]
>>
>> 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?
>>
>
> Use a stack?
>
> Whenever you start a new list, push the corresponding closing tag onto
> a stack.  Whenever your "indent level" decreases, pop the stack and
> write out the closing tag you get.
>
> It's straightforward to use a python list as a stack.

Or even simpler.

You keep track of your current indentation level (0, 1, ...). If
level==1 and you come to an indent: 2, you generate an <ul> and
increase level to 2.  Similarly for going left. When you reach the end
you add </ul>s to go back up to level 1 (or maybe you want to call it
level 0 instead).

That probably assumes you use HTML (like you say) rather than XHTML
(which your example hints at).  In HTML you don't need to supply the
</li>s.

I did all this in Perl earlier today, but in my case it was unsuitable
because I skipped levels (had a list of HTML headings, wanted a
table-of-contents, but sometimes a <h1> was followed by <h3> with no
<h2> inbetween. I'd get invalid stuff like <ul><ul>.

/Jorgen

-- 
  // Jorgen Grahn <grahn@  Oo  o.   .  .
\X/     snipabacken.se>   O  o   .



More information about the Python-list mailing list