About
HTE (HTML Treebuilder Engine) provides an easy way to programatically build HTML document trees.
HTE provides an Html Tree object which is used to generate and manage nodes on the HTML document tree. Nodes may be:
render()
methodTo create tag elements, use the tree object and a method name matching the tag. E.g.,
from hte import Html5TreeBuilder
tb = Html5TreeBuilder()
doc = tb.html()
doc.add(tb.body(tb.h1("Hello"), tb.p("This is a story ...")))
print(doc.render())
to produce (pretty printed):
<html>
<body>
<h1>Hello</h1>
<p>This is a story ...</p>
</body>
</html>
Closing tags are handled according to the various specs (HTML5, XHTML, XML) as are attribute names and quoting.
Text strings are first class nodes but have no children and are appropriately escaped. Raw strings are first class nodes but have no children and are not escaped.
A tree may be rendered at any time to produce an ordered flat list of nodes. The most common output operation will be to generate a string to produce a complete or partial HTML document.
The code is intentionally minimal. HTE is meant to be lean and lightweight.
There is currently no support for validating the nodes of the tree with respect to attributes, hierarchical relationships, or required elements of a fully compliant HTML page.
Various tree builders are available, each with their own configuration.
Configuration Setting | Html5TreeBuilder | XHtml5TreeBuilder | XmlTreeBuilder |
---|---|---|---|
anytag (allow any tag) |
No | No | Yes |
attrminimize (automatically minimize attribute names) |
Yes | Yes | No |
ignorecase (ignore tag case) |
Yes | No | No |
lowercase (automatically lowercase tag name) |
Yes | Yes | No |
opttags (optional tags) |
Yes | No | No |
tags (list of tags) |
HTML5 | HTML5 | None |
voidtags (list of void tags) |
HTML5 | HTML5 | None |
To tabulate all environment variables:
import os
from hte import Html5TreeBuilder
tb = Html5TreeBuilder()
doc = tb.html()
body = doc.add(tb.body(tb.h1("Env")))
table = body.add(tb.table(tb.tr(tb.th("Name"), tb.th("Value"))))
table.add([tb.tr(tb.td(k), tb.td(v)) for k, v in sorted(os.environ.items())])
print(doc.render())
For more, see here.