Tuesday, September 22, 2009

Simply HTML

Generating HTML markup in Python applications does not always mean resorting to rendering templates. Using templates to implement the views of an application on the web is a standard practice because it helps to remove the presentation layer. That being said, there is nothing to stop a standard Python module from generating markup while only being concerned with the presentation, not the application logic.

The html Python package provides a very simplistic method in which to generate HTML pragmatically. There is nothing wrong with using this approach as long as the separation of concerns principal is obeyed. This Python package allows developers to generate markup with a single HTML class. This class isn't meant to act as a singleton, but, rather, as a logically-separated string. There is nothing preventing developers from combining HTML instances to provide the final rendering.

The two main features of these HTML instances are that they use simple element methods to construct elements. This adds a nice self-containment to the document while it is under construction. The HTML instances also support the with statement. This provides a context for building child elements as is illustrated below.
#Example; Using the html package.

#Get the HTML class.
from html import HTML

if __name__=="__main__":
#Instantiate an HTML document.

#Construct a HTML element and provide a context.
with html_obj.html():

#Construct a body element with a class,
#and provide a context.
with html_obj.body(klass="my-body"):

#Construct some body elements.
html_obj.h1("Testing 123", klass="my-header")
html_obj.p("Hello World!", klass="my-text")

#Display the markup.
print html_obj