Build

Construct HTML trees in code, the way lxml.builder.E does. The builder is a thin layer over Element and serialize(): E.<tag>(attrs, *children) builds a real element, folds a leading mapping into its attributes, and appends each remaining argument as a child – a string becomes a Text node, and any node is appended as-is. The result is an ordinary turbohtml tree, so it queries, edits, and serializes like a parsed one.

turbohtml.build.E: Final

The shared builder: E.div(...) or E("div", ...) builds a <div> element.

class turbohtml.build.ElementMaker

A factory whose attribute access names the tag to build: E.div returns a callable that builds a <div>.

Use the singleton E, or instantiate a private maker. E.section(...) and E("section", ...) are equivalent; the call form takes a tag that is not a Python identifier.

turbohtml.build.document(*, title=None, lang=None, charset='utf-8', head=(), body=())

Build a complete HTML5 document around the given head and body content.

Where E builds a bare fragment, this scaffolds the whole page: a <!DOCTYPE html> followed by <html> holding a <head> and a <body>. The head leads with a <meta charset> and a <title> (when supplied), then the head content; the body holds the body content. The result is a turbohtml.Document, so document(...).serialize() emits the doctype and the full shell:

from turbohtml.build import E, document

page = document(title="Report", lang="en", body=[E.h1("Sales"), E.p("Up 4%")])
page.serialize()
# <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Report</title></head>
# <body><h1>Sales</h1><p>Up 4%</p></body></html>
Parameters:
  • title (str | None) – the <title> text; None omits the element.

  • lang (str | None) – the lang attribute for <html>; None omits it.

  • charset (str | None) – the <meta charset> value; None omits the meta element (e.g. when the charset is set by an HTTP header instead).

  • head (Iterable[Content]) – extra <head> content, appended after the meta and title; a string becomes a turbohtml.Text node.

  • body (Iterable[Content]) – the <body> content; a string becomes a turbohtml.Text node.

Return type:

Document

Returns:

the assembled turbohtml.Document.

Raises:

TypeError – if title, lang, or charset is neither a str nor None, or a head or body item is not a node or string.