Mimsy Were the Borogoves

Hacks: Articles about programming in Python, Perl, PHP, and whatever else I happen to feel like hacking at.

Object-oriented HTML with Python

Jerry Stratton, March 15, 2005

When I chose to write the character management software for my role-playing game in Python instead of (most likely) PHP, I also had to face not being able to so easily intersperse HTML and programming code.

Rather than work up something PHP-like for Python, I decided to try and take advantage of the features that drew me to Python for this project: objects, inheritance, and scope.

Good HTML is hierarchical; HTML elements contain other HTML elements and do not cross over HTML elements.

Hello World

Here is your basic hello, world! script. It creates a HEAD and a BODY part for the web page, and them combines them into an HTML part.

  • import makeHTML
  • pageTitle = 'Hello World'
  • pageHead = makeHTML.part('head')
  • pageHead.addPart('title', content=pageTitle)
  • pageBody = makeHTML.part('body')
  • pageBody.addPart('h1', content=pageTitle)
  • pageBody.addPart('p', content="Oh no, not again!")
  • pageBody.addPart('hr')
  • fullPage = makeHTML.part('html')
  • fullPage.addPiece(pageHead)
  • fullPage.addPiece(pageBody)
  • fullPage.make()

This will produce the HTML code: