in reply to •Re: Hash to HTML display
in thread Hash to HTML display

Maybe I'm a little too picky here, but I want to encourage everybody to write "right" HTML; with XHTML in mind, of course.. I edited merlyn's code so it creates XHTML conform output:

sub hash_to_html ($;$) { my $x = shift; my $i = @_ ? shift : ''; return "" unless ref ($x) eq "HASH"; return "$i<ul>\n" . join ('', map { "$i <li>$_</li>\n" . hash_to_html ($x->{$_}, "$ +i ") } sort (keys (%$x))) . "$i</ul>\n"; }

Which prints (with the input above):

<ul> <li>Cows</li> <ul> <li>Brown</li> <li>Green</li> <li>Orange</li> <li>Strawberry</li> <ul> <li>Solid</li> <li>Spotted</li> </ul> </ul> <li>Dogs</li> <ul> <li>Purple</li> <ul> <li>Solid</li> <li>Spotted</li> </ul> </ul> </ul>

Regards,
-octo

Replies are listed 'Best First'.
•Re: Re: Hash to (X)HTML display
by merlyn (Sage) on Jul 18, 2002 at 14:57 UTC
    No, you've got the /LI in the wrong place. Change
    join ('', map { "$i <li>$_</li>\n" . hash_to_html ($x->{$_}, "$i " +) } sort (keys (%$x)))
    to
    join ('', map { "$i <li>$_\n" . hash_to_html ($x->{$_}, "$i ")."$i + </li>" } sort (keys (%$x)))

    -- Randal L. Schwartz, Perl hacker

      Oh, right.. I don't do lists all that often, but these not-closed li-tags just bugged me :)

      Regards, -octo

•Re: Re: Hash to (X)HTML display
by merlyn (Sage) on Jul 18, 2002 at 17:46 UTC
    but I want to encourage everybody to write "right" HTML
    Hmm. You are aware that in HTML, the close tag on an LI element is completely optional, and still validates? So it's "right" HTML. Truly. It's not tag soup with error correction. It really is "right" HTML.

    Surely it's not XHTML, but the rules are different there. No optional close tags, for example. And all your attributes must be quoted. And a few other miscellaneous things.

    But the original request was for HTML, so I kept my version of the program simple.

    -- Randal L. Schwartz, Perl hacker