recommended way of generating HTML from Python

Robert Brewer fumanchu at amor.org
Mon Feb 21 13:07:14 EST 2005


Michele Simionato wrote:
> The problem is a problem of standardization, indeed.
> There are plenty of recipes to do the same job, I just
> would like to use a blessed one (I am teaching a Python
> course and I do not know what to recommend to my students).

Wouldn't we *all* like all of our problems worked out for us. ;)

> class HTMLTag(object):
>     [wonderful code snipped]

That's a reasonable start, and you have some fun magic in there, but I think you're going to hit a wall of complexity Real Soon Now--elements without a separate closing tag, safe attribute quoting, and general usability pressures will start to bite you. I note also what Kent said about separation, and the desire to "hand things off to a web designer".

In my own work, I tried to meet both of these concerns with a single Assembly class, which you can see at http://www.aminus.org/rbre/cation/html/assembly.py. At its most basic, it is nothing more than a namespace plus a template. I think it solves the separation issue nicely by allowing the template to be loaded from a file, whether that file be HTML from a designer, HTML "bulding blocks" which a developer might supply, or even CSS, or an email template. But it also allows for useful subclassing, for code generation. Here's an example: the subclass for "hidden input" elements:

class HiddenElement(Assembly):
    """An Assembly for generating HTML <input type='hidden'> elements
    
    Usage:
        output = assembly.HiddenElement(app).assemble_all(key)
    """
    
    templateText = u'<input type="hidden" name=%(name)s value=%(value)s />'
    
    def assemble_all(self, name, value):
        return self.assemble({u'name': html.quote(name),
                              u'value': html.quote(value)})

The "assemble_all" method allows the developer to focus on the important bits (name and value) and forget the implementation details. Check out the TableRows class for a more complex example, whereby an HTML table can be built incrementally, inline with the data access logic.

Now, getting into usability concerns (that framework and library authors tend to obsess over ;) may be too advanced for your class at the moment. But that's why recipes are recipes, not standard library modules: they're often biased toward quick and dirty scripting, not usable, maintainable edifices.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list