Python HTML generator

Solution 1:

Dominate is an HTML generation library that lets you easily create tags. In dominate, python reserved words are prefixed with an underscore, so it would look like this:

from dominate.tags import *
t = div(table(_id="the_table"), _class="tbl")
print(t)


<div class="tbl">
  <table id="the_table"></table>
</div>

Disclaimer: I am the author of dominate

Solution 2:

If you want programmatic generation rather than templating, Karrigell's HTMLTags module is one possibility; it can include e.g. the class attribute (which would be a reserved word in Python) by the trick of uppercasing its initial, i.e., quoting the doc URL I just gave:

Attributes with the same name as Python keywords (class, type) must be capitalized :

print DIV('bar', Class="title")  ==>  <DIV class="title">bar</DIV>

Solution 3:

HTML Generation is usually done with one of the infinite amounts of HTML templating languages available for Python. Personally I like Templess, but Genshi is probably the most popular. There are infinite amounts of them, there is a list which is highly likely to be incomplete.

Otherwise you might want to use lxml, where you can generate it in a more programmatically XML-ish way. Although I have a hard time seeing the benefit.

Solution 4:

There's the venerable HTMLGen by Robin Friedrich, which is hard to find but still available here (dated 2001, but HTML hasn't changed much since then ;-). There's also xist. Of course nowadays HTML generation, as Lennart points out, is generally better done using templating systems such as Jinja or Mako.