What Is HTE?

HTE (HTML Treebuilder Engine) provides an easy way to programatically build HTML document trees.

How Does HTE Work?

HTE provides an Html Tree object which is used to generate and manage nodes on the HTML document tree. Nodes may be:

  • tag elements
  • text strings
  • raw strings
  • an arbitrary object supporting the render() method

To 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.

Example

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 Tree Builder Examples.

Tags:
    

Contact

About

Name

HTE - HTML Tree Engine

Requirements

Python 2.x

License

BSD 2-Clause

Links

Repository