3.2 Hello Friends

The previous example is extended to greet several friends.

import crawdad
class HelloFriendsDoc (crawdad.HtmlDocument):
    def __init__ (self, friendList):
        self.friends = friendList
        crawdad.HtmlDocument.__init__ (self)
    def mainBody (self):
        helloList = self.UL ()
        for aFriend in self.friends:
            helloList.append (self.helloFriend (aFriend))
        return helloList
    def helloFriend (self, aFriend):
        return self.LI ("Hello " +  aFriend)

To generate the HTML, create a HelloFriendsDoc object with a list of friends (Bob, Carol, ...) and call its printHtml method.

>>> friends = ["Bob", "Carol", "Ted", "Alice"]
>>> doc = HelloFriendsDoc (friends)
>>> doc.printHtml ()
<HTML><HEAD><TITLE>Untitled document</TITLE>
<BODY><UL><LI>Hello Bob</LI>
<LI>Hello Carol</LI>
<LI>Hello Ted</LI>
<LI>Hello Alice</LI>

The resulting HTML is complete and correctly nested. Crawdad starts new lines after tags like </HEAD> and </LI> to aid visual inspection.

The mainBody method returns a <UL> (unordered list) that contains a <LI> (list item) for each friend. The UL and LI methods generate HtmlElement objects for the respective HTML tags.

The helloList initially has no content, but <LI> HtmlElement objects are appended one-by-one. The helloFriend method creates these <LI> HtmlElement objects with some initial text content.

Most HtmlElement objects can contain other HtmlElement objects or text. For example, a <P> HtmlElement object could contain some text, a <B> object (with its own content), and more text. HtmlElement objects can be initialized empty or with content. Additional content can be prepended to the front of a content list or appended to the end.

HtmlElement's content flexibility allows a simplification of the mainBody method. Python's map function applies the helloFriend method to each friend and returns a list of <LI> objects. The <UL> is initialized with this content and returned as the main body of the document.

    def mainBody (self):
        return self.UL (map (self.helloFriend, self.friends))