Next / Previous / Contents / TCC Help System / NM Tech homepage

10.4. webPage(): Create an empty XHTML page

This function builds a generic page of XHTML, to which other functions can add content later. It returns a 2-tuple (doc, body)): doc is an et.ElementTree instance containing the whole page, and body is the body element of that page as an et.Element instance.

catweb
# - - -   w e b P a g e

def webPage(titleText, stylesheet):
    '''Builds the skeleton of an XHTML page.

      [ (titleText is the text for the title and h1 elements) and
        (stylesheet is the href of the stylesheet) ->
          return (a new XHTML page with that title and stylesheet
          as an et.ElementTree, the body element of that page as an
          et.Element) ]
    '''

Document creation is described in Python XML processing with lxml. We'll even put in a DOCTYPE so the W3C validator will approve.

catweb
    #-- 1
    # [ doc  :=  a new et.ElementTree containing an html root
    #       element in turn containing a head element with
    #       title (titleText) and stylesheet (stylesheet)
    #   root  :=  that root element ]
    root = E.html({'xmlns': 'http://www.w3.org/1999/xhtml'},
        E.head(
            E.title(titleText),
            E.link(rel='stylesheet', href=stylesheet, type='text/css')))
    doc = et.ElementTree(root)            

Next we set up the body element, and place the page title within an h1.

catweb
    #-- 2
    # [ root  :=  root with a new body element added which in turn
    #       contains an h1 with (titleText)
    #   body  :=  that body element ]
    body = subElement(root,
        E.body(
            E.h1(titleText)))

    #-- 3
    return (doc, body)