API reference

html5

HTML5 document and CSS3 helpers.

html5.document

HTML5 document primitives.

This module provides the core building blocks for constructing HTML5 documents programmatically. The primary entry point is HtmlDocument, which manages a title, a language attribute, head nodes, and body nodes and renders the complete <!doctype html> output.

Leaf node types—Text, Raw, Comment, Doctype, and Element—all derive from Node and implement a render() method that returns a string of HTML.

Helper factory functions (text(), raw(), comment(), doctype_node(), element()) are thin wrappers around the node classes and are the preferred way to build nodes inline.

class html5.document.Comment(value)[source]

Bases: Node

An HTML comment node.

Example:

Comment(" TODO: remove this ").render()  # "<!-- TODO: remove this -->"
Parameters:

value (str)

render()[source]

Return the HTML comment string.

Return type:

str

value: str
class html5.document.Doctype(value='html')[source]

Bases: Node

A doctype declaration node.

Defaults to the standard HTML5 doctype. Pass a custom value for legacy or XHTML doctypes.

Example:

Doctype().render()         # "<!doctype html>"
Doctype("html").render()   # "<!doctype html>"
Parameters:

value (str)

render()[source]

Return the doctype declaration string.

Return type:

str

value: str = 'html'
class html5.document.Element(tag, children=(), attributes=<factory>, void=False)[source]

Bases: Node

An HTML element with optional children and attributes.

Attribute names follow Python identifier rules with two normalisation steps applied automatically:

  • A trailing underscore is stripped (class_class).

  • Remaining underscores are replaced with hyphens (data_foodata-foo).

Attribute values follow these rules:

  • None or False — the attribute is omitted entirely.

  • True — the attribute is rendered as a boolean attribute (no value).

  • Any other value — rendered as a quoted string, HTML-escaped.

Void elements (<br>, <img>, <input>, …) are rendered without a closing tag when void is True.

Example:

Element("p", (Text("Hello"),), {"class": "lead"}).render()
# '<p class="lead">Hello</p>'

Element("br", void=True).render()
# '<br>'
Parameters:
attributes: Mapping[str, Any]
children: tuple[Node | str, ...] = ()
render()[source]

Return the rendered HTML element string.

Return type:

str

tag: str
void: bool = False
class html5.document.HtmlDocument(title='', lang='en', head_nodes=<factory>, body_nodes=<factory>)[source]

Bases: object

A complete, renderable HTML5 document.

The document always emits a <!doctype html> declaration and a <meta charset="utf-8"> tag. The title is placed inside <title> in the document head. Additional head and body content is appended with add_head() and add_body().

Example:

from html5 import HtmlDocument, Div, H1, style_tag, CSSStyleSheet

sheet = CSSStyleSheet().add_rule("body", margin="0")
doc = (
    HtmlDocument(title="My page")
    .add_head(style_tag(sheet))
    .add_body(Div(H1("Hello, world!")))
)
print(doc.render())
Parameters:
add_body(*nodes)[source]

Append one or more nodes to the document body.

Parameters:

*nodes (Node | str) – Node instances or raw HTML strings to add.

Returns:

This document (for method chaining).

Return type:

HtmlDocument

add_head(*nodes)[source]

Append one or more nodes to the document head.

Parameters:

*nodes (Node | str) – Node instances or raw HTML strings to add.

Returns:

This document (for method chaining).

Return type:

HtmlDocument

body_nodes: list[Node | str]

Nodes placed inside the document <body>.

head_nodes: list[Node | str]

Nodes appended to the document <head> after the charset meta and title.

lang: str = 'en'

The lang attribute on the root <html> element. Defaults to "en".

render()[source]

Render the complete HTML5 document as a string.

Always prepends <!doctype html> and includes <meta charset="utf-8">.

Returns:

The full HTML document string.

Return type:

str

title: str = ''

The page title placed inside <title> in the document head.

class html5.document.Node[source]

Bases: object

Abstract base class for all HTML document nodes.

Every node implements render() which returns a plain string of HTML. Leaf nodes are immutable frozen dataclasses; HtmlDocument is the only mutable container.

render()[source]

Return the HTML string for this node.

Raises:

NotImplementedError – Subclasses must override this method.

Return type:

str

class html5.document.Raw(value)[source]

Bases: Node

A raw HTML node whose content is inserted without escaping.

Use this only for content you trust completely — for example HTML rendered by another part of this library. User-supplied strings should use Text instead.

Example:

Raw("<strong>bold</strong>").render()  # "<strong>bold</strong>"
Parameters:

value (str)

render()[source]

Return the raw HTML string unchanged.

Return type:

str

value: str
class html5.document.Text(value)[source]

Bases: Node

An HTML-escaped text node.

The value is escaped with html.escape() so that characters such as <, >, and & are converted to their HTML entities and cannot be interpreted as markup.

Example:

Text("Hello <world>").render()  # "Hello &lt;world&gt;"
Parameters:

value (str)

render()[source]

Return the HTML-escaped text string.

Return type:

str

value: str
html5.document.comment(value)[source]

Create an HTML comment node.

Parameters:

value (str) – The comment text (without the <!-- / --> delimiters).

Returns:

A Comment node.

Return type:

Comment

html5.document.doctype()[source]

Return the HTML5 doctype declaration string.

Returns:

The literal string "<!doctype html>".

Return type:

str

html5.document.doctype_node(value='html')[source]

Create a doctype declaration node.

Parameters:

value (str) – The doctype identifier. Defaults to "html" for HTML5.

Returns:

A Doctype node.

Return type:

Doctype

html5.document.element(tag, *children, void=False, **attributes)[source]

Create an HTML element node.

Attribute names are normalised: trailing underscores are stripped and remaining underscores are replaced with hyphens, so data_value="x" becomes data-value="x" and class_="btn" becomes class="btn".

Parameters:
  • tag (str) – The HTML tag name (e.g. "div", "span").

  • *children (Node | str) – Child nodes or plain strings. Strings are text-escaped automatically.

  • void (bool) – If True the element is rendered without a closing tag.

  • **attributes (Any) – HTML attributes as keyword arguments.

Returns:

An Element node.

Return type:

Element

Example:

element("a", "Click me", href="/home", class_="nav-link").render()
# '<a href="/home" class="nav-link">Click me</a>'
html5.document.raw(value)[source]

Create a raw (unescaped) HTML node.

Parameters:

value (str) – A trusted HTML string to insert verbatim.

Returns:

A Raw node.

Return type:

Raw

html5.document.text(value)[source]

Create an HTML-escaped text node.

Parameters:

value (str) – The plain text string to escape and render.

Returns:

A Text node.

Return type:

Text

html5.css

CSS3 stylesheet helpers.

This module provides a tree of immutable CSS node classes that mirrors the structure of a CSS stylesheet: declarations, rules, at-rules, keyframes, and complete stylesheets. Every node implements render() which returns a plain CSS string.

The mutable CSSStyleSheet accumulates nodes and renders them as a complete stylesheet. Use it with style_tag() to embed styles in an HtmlDocument, or with MarkupWriter to write a .css file to disk.

CSS custom properties (variables) are supported via CSSCustomProperties and the css_var() helper:

from html5 import CSSStyleSheet, css_var

sheet = (
    CSSStyleSheet()
    .add_custom_properties({"--size-1": "0.25rem", "--color-brand": "#005fcc"})
    .add_rule("button", ("padding", css_var("--size-1")))
)
html5.css.BOOTSTRAP5_CSS_URL = 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css'

The jsDelivr CDN URL for Bootstrap 5.3.3 CSS.

class html5.css.CSSAtRule(name, prelude='', body=(), block=True)[source]

Bases: CSSNode

A generic CSS at-rule (@name prelude { body } or @name prelude;).

Use the specialised subclasses (CSSMediaRule, CSSSupportsRule, CSSLayerRule, CSSImportRule, CSSKeyframesRule) for common at-rules. Use this class directly for less common ones such as @charset.

Parameters:
  • name (str) – The at-rule name, with or without the leading @. Underscores are replaced with hyphens.

  • prelude (str) – Optional text between the rule name and the block or semicolon.

  • body (tuple[CSSNode | str, ...]) – Child nodes or strings rendered inside the block.

  • block (bool) – If True (default) renders a { body } block; if False renders a semicolon-terminated statement.

Example:

CSSAtRule("charset", '"UTF-8"', block=False).render()
# '@charset "UTF-8";'
block: bool = True
body: tuple[CSSNode | str, ...] = ()
name: str
prelude: str = ''
render()[source]

Return the at-rule CSS string.

Return type:

str

class html5.css.CSSComment(value)[source]

Bases: CSSNode

A CSS comment node.

Example:

CSSComment("Reset styles").render()
# "/* Reset styles */"
Parameters:

value (str)

render()[source]

Return the CSS comment string.

Return type:

str

value: str
class html5.css.CSSCustomProperties(props, selector=':root')[source]

Bases: CSSNode

A block of CSS custom properties (variables) on a selector.

Renders a selector { --name: value; ... } block. The selector defaults to :root so the variables are available document-wide.

Pass a plain dict mapping --name strings to their values. Use css_var() to reference them in other declarations.

Parameters:
  • props (Mapping[str, Any]) – A mapping of custom property names to values.

  • selector (str) – The CSS selector for the block. Defaults to ":root".

Example:

CSSCustomProperties(
    {"--size-1": "0.25rem", "--color-brand": "#005fcc"},
).render()
# ":root { --size-1: 0.25rem; --color-brand: #005fcc; }"

CSSCustomProperties({"--fg": "#fff"}, selector="[data-theme='dark']")
properties: tuple[tuple[str, Any], ...]
render()[source]

Return the CSS custom-properties block string.

Return type:

str

selector: str
class html5.css.CSSDeclaration(property_name, value, important=False)[source]

Bases: CSSNode

A single CSS property–value declaration.

Property names are normalised: underscores are replaced with hyphens, so font_size becomes font-size. CSS custom property names (starting with --) pass through unchanged.

Parameters:
  • property_name (str) – The CSS property name (e.g. "color", "--size-1").

  • value (Any) – The CSS value. None causes the declaration to render as an empty string (the declaration is skipped).

  • important (bool) – If True appends !important to the value.

Example:

CSSDeclaration("font_size", "1rem").render()   # "font-size: 1rem;"
CSSDeclaration("--size-1", "0.25rem").render() # "--size-1: 0.25rem;"
CSSDeclaration("color", "red", important=True).render()
# "color: red !important;"
important: bool = False
property_name: str
render()[source]

Return the CSS declaration string, or an empty string if value is None.

Return type:

str

value: Any
class html5.css.CSSImportRule(url, media='')[source]

Bases: CSSAtRule

A CSS @import rule.

Parameters:
  • url (str) – The URL of the stylesheet to import.

  • media (str) – An optional media query string appended after the URL.

Example:

CSSImportRule("reset.css").render()
# '@import url("reset.css");'

CSSImportRule("print.css", media="print").render()
# '@import url("print.css") print;'
class html5.css.CSSInlineStyle(*declarations)[source]

Bases: CSSNode

A sequence of CSS declarations for use in a style attribute.

Accepts the same declaration forms as CSSRule: a CSSDeclaration, a (name, value) tuple, or a single-key mapping.

Use inline_style() for a convenience wrapper that returns a string directly suitable for the style attribute.

Example:

CSSInlineStyle(("color", "red"), ("font_size", "1rem")).render()
# "color: red; font-size: 1rem;"
Parameters:

declarations (tuple[CSSDeclaration | tuple[str, Any] | Mapping[str, Any], ...])

declarations: tuple[CSSDeclaration | tuple[str, Any] | Mapping[str, Any], ...] = ()
render()[source]

Return the inline style string (without the style="" wrapper).

Return type:

str

class html5.css.CSSKeyframe(selector, *declarations)[source]

Bases: CSSNode

A single keyframe stop inside a CSSKeyframesRule.

Parameters:

Example:

CSSKeyframe("from", ("opacity", 0)).render()
# "from { opacity: 0; }"
declarations: tuple[CSSDeclaration | tuple[str, Any] | Mapping[str, Any], ...] = ()
render()[source]

Return the keyframe CSS string.

Return type:

str

selector: str
class html5.css.CSSKeyframesRule(name, frames=())[source]

Bases: CSSNode

A CSS @keyframes rule.

Parameters:

Example:

CSSKeyframesRule(
    "fade",
    frames=(CSSKeyframe("from", ("opacity", 0)), CSSKeyframe("to", ("opacity", 1))),
).render()
# "@keyframes fade { from { opacity: 0; } to { opacity: 1; } }"
frames: tuple[CSSKeyframe, ...] = ()
name: str
render()[source]

Return the @keyframes rule CSS string.

Return type:

str

class html5.css.CSSLayerRule(layer='', *rules)[source]

Bases: CSSAtRule

A CSS @layer block.

Parameters:
  • layer (str) – The layer name. Omit for an anonymous layer.

  • *rules (CSSNode | str) – Child CSSNode instances or CSS strings.

Example:

CSSLayerRule("utilities", CSSRule(".hidden", ("display", "none"))).render()
# "@layer utilities { .hidden { display: none; } }"

Bases: CSSNode

A <link rel="stylesheet"> element node.

Parameters:
  • href (str) – The URL of the stylesheet.

  • rel (str) – The rel attribute value. Defaults to "stylesheet".

  • attributes (Mapping[str, Any]) – Additional HTML attributes for the <link> element.

Example:

CSSLink(href="styles.css").render()
# '<link rel="stylesheet" href="styles.css">'
attributes: Mapping[str, Any]
href: str
rel: str = 'stylesheet'
render()[source]

Return the rendered <link> element string.

Return type:

str

class html5.css.CSSMediaRule(query, *rules)[source]

Bases: CSSAtRule

A CSS @media block.

Parameters:
  • query (str) – The media query string (e.g. "screen and (min-width: 40rem)").

  • *rules (CSSNode | str) – Child CSSNode instances or CSS strings.

Example:

CSSMediaRule(
    "(prefers-color-scheme: dark)",
    CSSRule("body", ("background", "#000")),
).render()
# "@media (prefers-color-scheme: dark) { body { background: #000; } }"
class html5.css.CSSNode[source]

Bases: object

Abstract base class for all CSS document nodes.

Every subclass implements render() which returns a plain CSS string.

render()[source]

Return the CSS string for this node.

Raises:

NotImplementedError – Subclasses must override this method.

Return type:

str

class html5.css.CSSRule(selector, *declarations)[source]

Bases: CSSNode

A CSS selector rule with one or more declarations.

Accepts three declaration forms:

  • A CSSDeclaration instance.

  • A (property_name, value) tuple.

  • A single-key Mapping {"property_name": value}.

Property names are normalised: underscores become hyphens.

Parameters:

Example:

CSSRule("body", ("margin", 0), ("font_family", "system-ui")).render()
# "body { margin: 0; font-family: system-ui; }"
declarations: tuple[CSSDeclaration | tuple[str, Any] | Mapping[str, Any], ...] = ()
render()[source]

Return the CSS rule string.

Return type:

str

selector: str
class html5.css.CSSStyleElement(stylesheet)[source]

Bases: CSSNode

A complete <style> element wrapping a stylesheet or CSS node.

Prefer style_tag() over this class directly, as style_tag() avoids double-wrapping when passed a CSSStyleElement.

Parameters:

stylesheet (CSSNode | str) – A CSSNode or raw CSS string to wrap.

Example:

CSSStyleElement(CSSStyleSheet().add_rule("p", ("color", "red"))).render()
# "<style>p { color: red; }</style>"
render()[source]

Return the <style> element HTML string.

Return type:

str

stylesheet: CSSNode | str
class html5.css.CSSStyleSheet(rules=<factory>)[source]

Bases: CSSNode

A mutable CSS stylesheet that accumulates rules and renders them in order.

Build a stylesheet by chaining the add_* methods, then pass it to style_tag() for embedding in an HTML document or to MarkupWriter for writing to disk.

Example:

from html5 import CSSStyleSheet, css_var, style_tag, HtmlDocument

sheet = (
    CSSStyleSheet()
    .add_custom_properties({"--brand": "#005fcc", "--gap": "1rem"})
    .add_comment("Base styles")
    .add_import("reset.css")
    .add_rule("body", margin="0", font_family="system-ui")
    .add_rule("a", ("color", css_var("--brand")))
    .add_media("(prefers-color-scheme: dark)", CSSRule("body", ("background", "#111")))
)
doc = HtmlDocument(title="Example").add_head(style_tag(sheet))
Parameters:

rules (list[CSSNode | str])

add(*items)[source]

Append one or more raw nodes or strings to the stylesheet.

Parameters:

*items (CSSNode | str) – CSSNode instances or raw CSS strings.

Returns:

This stylesheet (for method chaining).

Return type:

CSSStyleSheet

add_comment(value)[source]

Append a CSS comment.

Parameters:

value (str) – The comment text (without /* */ delimiters).

Returns:

This stylesheet (for method chaining).

Return type:

CSSStyleSheet

add_custom_properties(props, selector=':root')[source]

Append a CSS custom-properties block.

Parameters:
  • props (Mapping[str, Any]) – A mapping of --name strings to their CSS values.

  • selector (str) – The selector for the block. Defaults to ":root".

Returns:

This stylesheet (for method chaining).

Return type:

CSSStyleSheet

Example:

sheet.add_custom_properties({"--size-1": "0.25rem", "--color-brand": "#005fcc"})
add_import(url, media='')[source]

Append a CSS @import rule.

Parameters:
  • url (str) – The URL of the stylesheet to import.

  • media (str) – An optional media query string.

Returns:

This stylesheet (for method chaining).

Return type:

CSSStyleSheet

add_keyframes(name, *frames)[source]

Append a CSS @keyframes rule.

Parameters:
Returns:

This stylesheet (for method chaining).

Return type:

CSSStyleSheet

add_layer(layer='', *rules)[source]

Append a CSS @layer block.

Parameters:
  • layer (str) – The layer name. Pass an empty string for an anonymous layer.

  • *rules (CSSNode | str) – Child nodes or CSS strings for the block body.

Returns:

This stylesheet (for method chaining).

Return type:

CSSStyleSheet

add_media(query, *rules)[source]

Append a CSS @media block.

Parameters:
  • query (str) – The media query string.

  • *rules (CSSNode | str) – Child nodes or CSS strings for the block body.

Returns:

This stylesheet (for method chaining).

Return type:

CSSStyleSheet

add_raw(css)[source]

Append a raw CSS string.

Use this for CSS that has no dedicated node class (e.g. a vendor-prefixed block or a one-off snippet).

Parameters:

css (str) – A raw CSS string to insert verbatim.

Returns:

This stylesheet (for method chaining).

Return type:

CSSStyleSheet

add_rule(selector, *declarations, **keyword_declarations)[source]

Append a CSS selector rule.

Declarations may be passed positionally (as CSSDeclaration, tuples, or single-key mappings) or as keyword arguments. Keyword argument names are normalised: underscores become hyphens.

Parameters:
  • selector (str) – The CSS selector (e.g. "body", ".btn").

  • *declarations (CSSDeclaration | tuple[str, Any] | Mapping[str, Any]) – Positional declarations.

  • **keyword_declarations (Any) – Keyword declarations — each key becomes a CSS property name after underscore→hyphen normalisation.

Returns:

This stylesheet (for method chaining).

Return type:

CSSStyleSheet

Example:

sheet.add_rule("body", margin="0", font_family="system-ui")
sheet.add_rule("h1", ("font_size", "2rem"), ("color", "#111"))
add_supports(condition, *rules)[source]

Append a CSS @supports block.

Parameters:
  • condition (str) – The supports condition string.

  • *rules (CSSNode | str) – Child nodes or CSS strings for the block body.

Returns:

This stylesheet (for method chaining).

Return type:

CSSStyleSheet

render()[source]

Render all rules in order as a newline-joined CSS string.

Return type:

str

rules: list[CSSNode | str]

The ordered list of CSS nodes in this stylesheet.

class html5.css.CSSSupportsRule(condition, *rules)[source]

Bases: CSSAtRule

A CSS @supports block.

Parameters:
  • condition (str) – The supports condition (e.g. "(display: grid)").

  • *rules (CSSNode | str) – Child CSSNode instances or CSS strings.

Example:

CSSSupportsRule(
    "(display: grid)",
    CSSRule("div", ("display", "grid")),
).render()
# "@supports (display: grid) { div { display: grid; } }"
html5.css.GOOGLE_FONTS_PRECONNECT_URL = 'https://fonts.googleapis.com'

The Google Fonts API preconnect URL.

html5.css.GOOGLE_FONTS_STATIC_URL = 'https://fonts.gstatic.com'

The Google Fonts static assets preconnect URL.

html5.css.TAILWIND_PLAY_CDN_URL = 'https://cdn.tailwindcss.com'

The Tailwind CSS Play CDN script URL.

html5.css.bootstrap5_stylesheet(version='5.3.3')[source]

Return a Bootstrap 5 stylesheet <link> node from jsDelivr.

Parameters:

version (str) – The Bootstrap version string. Defaults to "5.3.3".

Returns:

A CSSLink pointing to the Bootstrap CSS CDN URL.

Return type:

CSSLink

html5.css.css_var(name)[source]

Return a CSS var() reference for a custom property.

Parameters:

name (str) – The custom property name including the -- prefix (e.g. "--size-1").

Returns:

A string of the form "var(--size-1)".

Return type:

str

Example:

css_var("--color-brand")  # "var(--color-brand)"
html5.css.google_fonts_assets(*families, weights=(400, 500, 700), display='swap', text=None)[source]

Return the three <link> nodes required to load Google Fonts.

Returns a preconnect to fonts.googleapis.com, a crossorigin preconnect to fonts.gstatic.com, and the CSS stylesheet link — in the correct order for optimal font loading performance.

Parameters:
  • *families (str) – One or more font family names.

  • weights (Sequence[int]) – Font weights to request. Defaults to (400, 500, 700).

  • display (str) – The font-display strategy. Defaults to "swap".

  • text (str | None) – Optional character subset string for smaller downloads.

Returns:

(preconnect, crossorigin_preconnect, stylesheet).

Return type:

A 3-tuple of CSSLink nodes

Example:

doc.add_head(*google_fonts_assets("Inter"))
html5.css.google_fonts_url(*families, weights=(400, 500, 700), display='swap', text=None)[source]

Build a Google Fonts CSS2 API URL for the requested font families.

Parameters:
  • *families (str) – One or more font family names (e.g. "Inter", "Open Sans").

  • weights (Sequence[int]) – The font weights to request. Defaults to (400, 500, 700).

  • display (str) – The font-display value. Defaults to "swap".

  • text (str | None) – If provided, restricts the character set to the given string for smaller downloads.

Returns:

A Google Fonts CSS2 URL string.

Raises:

ValueError – If no font families are provided.

Return type:

str

Example:

google_fonts_url("Inter", "Open Sans", weights=(400, 700))
# "https://fonts.googleapis.com/css2?family=Inter:wght@400;700&..."
html5.css.inline_style(*declarations, **keyword_declarations)[source]

Render CSS declarations as a string for a style attribute.

Parameters:
Returns:

A CSS declaration string suitable for a style attribute value.

Return type:

str

Example:

inline_style(("border_radius", "8px"), color="red")
# "border-radius: 8px; color: red;"
html5.css.style_tag(stylesheet)[source]

Wrap a stylesheet or CSS node in a <style> tag.

If stylesheet is already a CSSStyleElement (which renders its own <style> wrapper), it is returned as-is to prevent double-wrapping.

Parameters:

stylesheet (CSSNode | str) – A CSSNode or raw CSS string to embed.

Returns:

A Raw node containing the <style> tag.

Return type:

Raw

Example:

sheet = CSSStyleSheet().add_rule("body", margin="0")
doc.add_head(style_tag(sheet))
html5.css.tailwind_script()[source]

Return the Tailwind CSS Play CDN <script> node.

Returns:

A JSScript loading the Tailwind Play CDN.

Return type:

JSScript

html5.js

JavaScript helpers for HTML documents.

Provides JSScript and convenience factory functions for common JavaScript patterns: external script tags, inline scripts, Bootstrap 5 bundle, and Google Charts loaders.

class html5.js.JSNode[source]

Bases: object

Abstract base class for JavaScript document nodes.

Every subclass implements render() which returns an HTML string.

render()[source]

Return the HTML string for this node.

Raises:

NotImplementedError – Subclasses must override this method.

Return type:

str

class html5.js.JSScript(src=None, code='', attributes=<factory>)[source]

Bases: JSNode

Render an inline or external JavaScript <script> tag.

Set src for an external script, or code for an inline script. Setting both raises ValueError. Additional HTML attributes (e.g. defer, type) may be passed via attributes.

Parameters:
  • src (str | None) – URL for an external script. Mutually exclusive with code.

  • code (str) – Inline JavaScript source. Mutually exclusive with src.

  • attributes (dict[str, Any]) – Extra HTML attributes for the <script> element.

Raises:

ValueError – If both src and code are provided.

Example:

JSScript(src="https://example.com/app.js").render()
# '<script src="https://example.com/app.js"></script>'

JSScript(code="console.log('hi')").render()
# "<script>console.log('hi')</script>"
attributes: dict[str, Any]
code: str = ''
render()[source]

Return the rendered <script> element HTML string.

Return type:

str

src: str | None = None
html5.js.bootstrap5_bundle_script(version='5.3.3')[source]

Return the Bootstrap 5 bundle <script> node from jsDelivr.

The bundle includes Popper.js, so no separate Popper script is required.

Parameters:

version (str) – The Bootstrap version string. Defaults to "5.3.3".

Returns:

A JSScript loading the Bootstrap bundle from jsDelivr CDN.

Return type:

JSScript

html5.js.google_charts_loader(version='51')[source]

Return the Google Charts loader <script> node.

This loads the Google Charts core loader. Call google_charts_package_loader() separately to request specific chart packages once the loader is present.

Parameters:

version (str) – The Google Charts loader version. Defaults to "51".

Returns:

A JSScript loading the Google Charts loader from gstatic.com.

Return type:

JSScript

html5.js.google_charts_package_loader(packages, callback=None)[source]

Return an inline Google Charts package-load snippet.

Renders an inline <script> that calls google.charts.load() for the specified packages. Optionally registers a callback via google.charts.setOnLoadCallback().

Parameters:
  • packages (Sequence[str]) – A sequence of Google Charts package names to load (e.g. ["corechart", "table"]).

  • callback (str | None) – Optional name of a JavaScript function to register as the on-load callback.

Returns:

A JSScript with the inline Google Charts loader snippet.

Return type:

JSScript

Example:

google_charts_package_loader(["corechart"], callback="drawChart")
# Renders an inline script calling google.charts.load(...)

Create an external <script> node.

Parameters:
  • src (str) – The URL of the external JavaScript file.

  • **attributes (Any) – Extra HTML attributes for the <script> element (e.g. defer=True, crossorigin="anonymous").

Returns:

A JSScript node referencing an external URL.

Return type:

JSScript

Example:

javascript_link("https://example.com/app.js", defer=True).render()
# '<script src="https://example.com/app.js" defer></script>'
html5.js.javascript_script(code, **attributes)[source]

Create an inline <script> node.

Parameters:
  • code (str) – The JavaScript source code to embed inline.

  • **attributes (Any) – Extra HTML attributes for the <script> element.

Returns:

A JSScript node with inline code.

Return type:

JSScript

Example:

javascript_script("console.log('hello')").render()
# "<script>console.log('hello')</script>"

html5.loader

File loaders that read HTML and CSS into html5 document objects.

html5.loader.css_loader(path)[source]

Read a CSS file and return a CSSStyleSheet.

The file content is stored as a single raw CSS block; no parsing of individual rules is performed.

Parameters:

path (str | Path) – Path to the CSS file to read.

Returns:

A CSSStyleSheet whose rendered output is the file content.

Return type:

CSSStyleSheet

html5.loader.html_loader(path)[source]

Read an HTML file and return an HtmlDocument.

The document title, lang attribute, head nodes, and body content are extracted from the file. The charset <meta> tag is stripped (since HtmlDocument.render() always emits one). All other head and body content is preserved as a single Raw node each.

Parameters:

path (str | Path) – Path to the HTML file to read.

Returns:

An HtmlDocument populated from the file.

Return type:

HtmlDocument

html5.writer

Utilities for writing rendered HTML and CSS to disk.

MarkupWriter provides a safe, root-anchored disk writer that prevents path traversal outside a configured base directory. Pass rendered HTML or CSS strings, or any object with a render() method, and the writer handles directory creation and encoding.

class html5.writer.MarkupWriter(root=PosixPath('.'), encoding='utf-8')[source]

Bases: object

Write rendered HTML and CSS content beneath a fixed root directory.

All paths passed to write methods must be relative to root. Absolute paths and .. traversal that would escape root are rejected with ValueError. Parent directories are created automatically.

Parameters:
  • root (Path) – The base directory under which all files are written. Defaults to the current working directory (".").

  • encoding (str) – The text encoding for written files. Defaults to "utf-8".

Example:

from html5 import CSSStyleSheet, HtmlDocument, MarkupWriter

writer = MarkupWriter(root="build")
doc = HtmlDocument(title="Hello").add_body("<p>Hello</p>")
sheet = CSSStyleSheet().add_rule("body", margin="0")

writer.write_html("index.html", doc)
writer.write_css("styles/site.css", sheet)
encoding: str
root: Path
write_css(path, stylesheet)[source]

Write rendered CSS to a file beneath the root directory.

Parameters:
  • path (str | Path) – A relative path for the output .css file.

  • stylesheet (Renderable | str) – An object with a render() method (e.g. CSSStyleSheet) or a plain CSS string.

Returns:

The absolute Path of the written file.

Return type:

Path

write_html(path, document)[source]

Write rendered HTML to a file beneath the root directory.

Parameters:
  • path (str | Path) – A relative path for the output .html file.

  • document (Renderable | str) – An object with a render() method (e.g. HtmlDocument) or a plain HTML string.

Returns:

The absolute Path of the written file.

Return type:

Path

write_text(path, content)[source]

Write a text string to a file beneath the root directory.

Parameters:
  • path (str | Path) – A relative path (from root) for the output file.

  • content (str) – The text content to write.

Returns:

The absolute Path of the written file.

Raises:

ValueError – If path is absolute or would escape the root directory via .. traversal.

Return type:

Path

class html5.writer.Renderable(*args, **kwargs)[source]

Bases: Protocol

Protocol for objects that can render themselves to a string.

render()[source]

Return the rendered string representation of this object.

Return type:

str

html5.elements

Generated HTML5 element classes.

class html5.elements.A(*children, **attributes)

Bases: Element

Render a <a> HTML element.

Parameters:
class html5.elements.Abbr(*children, **attributes)

Bases: Element

Render a <abbr> HTML element.

Parameters:
class html5.elements.Address(*children, **attributes)

Bases: Element

Render a <address> HTML element.

Parameters:
class html5.elements.Area(*children, **attributes)

Bases: Element

Render a <area> HTML element.

Parameters:
class html5.elements.Article(*children, **attributes)

Bases: Element

Render a <article> HTML element.

Parameters:
class html5.elements.Aside(*children, **attributes)

Bases: Element

Render a <aside> HTML element.

Parameters:
class html5.elements.Audio(*children, **attributes)

Bases: Element

Render a <audio> HTML element.

Parameters:
class html5.elements.B(*children, **attributes)

Bases: Element

Render a <b> HTML element.

Parameters:
class html5.elements.Base(*children, **attributes)

Bases: Element

Render a <base> HTML element.

Parameters:
class html5.elements.Bdi(*children, **attributes)

Bases: Element

Render a <bdi> HTML element.

Parameters:
class html5.elements.Bdo(*children, **attributes)

Bases: Element

Render a <bdo> HTML element.

Parameters:
class html5.elements.Blockquote(*children, **attributes)

Bases: Element

Render a <blockquote> HTML element.

Parameters:
class html5.elements.Body(*children, **attributes)

Bases: Element

Render a <body> HTML element.

Parameters:
class html5.elements.Br(*children, **attributes)

Bases: Element

Render a <br> HTML element.

Parameters:
class html5.elements.Button(*children, **attributes)

Bases: Element

Render a <button> HTML element.

Parameters:
class html5.elements.Canvas(*children, **attributes)

Bases: Element

Render a <canvas> HTML element.

Parameters:
class html5.elements.Caption(*children, **attributes)

Bases: Element

Render a <caption> HTML element.

Parameters:
class html5.elements.Cite(*children, **attributes)

Bases: Element

Render a <cite> HTML element.

Parameters:
class html5.elements.Code(*children, **attributes)

Bases: Element

Render a <code> HTML element.

Parameters:
class html5.elements.Col(*children, **attributes)

Bases: Element

Render a <col> HTML element.

Parameters:
class html5.elements.Colgroup(*children, **attributes)

Bases: Element

Render a <colgroup> HTML element.

Parameters:
class html5.elements.Data(*children, **attributes)

Bases: Element

Render a <data> HTML element.

Parameters:
class html5.elements.Datalist(*children, **attributes)

Bases: Element

Render a <datalist> HTML element.

Parameters:
class html5.elements.Dd(*children, **attributes)

Bases: Element

Render a <dd> HTML element.

Parameters:
class html5.elements.Del(*children, **attributes)

Bases: Element

Render a <del> HTML element.

Parameters:
class html5.elements.Details(*children, **attributes)

Bases: Element

Render a <details> HTML element.

Parameters:
class html5.elements.Dfn(*children, **attributes)

Bases: Element

Render a <dfn> HTML element.

Parameters:
class html5.elements.Dialog(*children, **attributes)

Bases: Element

Render a <dialog> HTML element.

Parameters:
class html5.elements.Div(*children, **attributes)

Bases: Element

Render a <div> HTML element.

Parameters:
class html5.elements.Dl(*children, **attributes)

Bases: Element

Render a <dl> HTML element.

Parameters:
class html5.elements.Dt(*children, **attributes)

Bases: Element

Render a <dt> HTML element.

Parameters:
class html5.elements.Em(*children, **attributes)

Bases: Element

Render a <em> HTML element.

Parameters:
class html5.elements.Embed(*children, **attributes)

Bases: Element

Render a <embed> HTML element.

Parameters:
class html5.elements.Fieldset(*children, **attributes)

Bases: Element

Render a <fieldset> HTML element.

Parameters:
class html5.elements.Figcaption(*children, **attributes)

Bases: Element

Render a <figcaption> HTML element.

Parameters:
class html5.elements.Figure(*children, **attributes)

Bases: Element

Render a <figure> HTML element.

Parameters:
class html5.elements.Footer(*children, **attributes)

Bases: Element

Render a <footer> HTML element.

Parameters:
class html5.elements.Form(*children, **attributes)

Bases: Element

Render a <form> HTML element.

Parameters:
class html5.elements.H1(*children, **attributes)

Bases: Element

Render a <h1> HTML element.

Parameters:
class html5.elements.H2(*children, **attributes)

Bases: Element

Render a <h2> HTML element.

Parameters:
class html5.elements.H3(*children, **attributes)

Bases: Element

Render a <h3> HTML element.

Parameters:
class html5.elements.H4(*children, **attributes)

Bases: Element

Render a <h4> HTML element.

Parameters:
class html5.elements.H5(*children, **attributes)

Bases: Element

Render a <h5> HTML element.

Parameters:
class html5.elements.H6(*children, **attributes)

Bases: Element

Render a <h6> HTML element.

Parameters:
class html5.elements.Head(*children, **attributes)

Bases: Element

Render a <head> HTML element.

Parameters:
class html5.elements.Header(*children, **attributes)

Bases: Element

Render a <header> HTML element.

Parameters:
class html5.elements.Hgroup(*children, **attributes)

Bases: Element

Render a <hgroup> HTML element.

Parameters:
class html5.elements.Hr(*children, **attributes)

Bases: Element

Render a <hr> HTML element.

Parameters:
class html5.elements.Html(*children, **attributes)

Bases: Element

Render a <html> HTML element.

Parameters:
class html5.elements.I(*children, **attributes)

Bases: Element

Render a <i> HTML element.

Parameters:
class html5.elements.Iframe(*children, **attributes)

Bases: Element

Render a <iframe> HTML element.

Parameters:
class html5.elements.Img(*children, **attributes)

Bases: Element

Render a <img> HTML element.

Parameters:
class html5.elements.Input(*children, **attributes)

Bases: Element

Render a <input> HTML element.

Parameters:
class html5.elements.Ins(*children, **attributes)

Bases: Element

Render a <ins> HTML element.

Parameters:
class html5.elements.Kbd(*children, **attributes)

Bases: Element

Render a <kbd> HTML element.

Parameters:
class html5.elements.Label(*children, **attributes)

Bases: Element

Render a <label> HTML element.

Parameters:
class html5.elements.Legend(*children, **attributes)

Bases: Element

Render a <legend> HTML element.

Parameters:
class html5.elements.Li(*children, **attributes)

Bases: Element

Render a <li> HTML element.

Parameters:

Bases: Element

Render a <link> HTML element.

Parameters:
class html5.elements.Main(*children, **attributes)

Bases: Element

Render a <main> HTML element.

Parameters:
class html5.elements.Map(*children, **attributes)

Bases: Element

Render a <map> HTML element.

Parameters:
class html5.elements.Mark(*children, **attributes)

Bases: Element

Render a <mark> HTML element.

Parameters:
class html5.elements.Menu(*children, **attributes)

Bases: Element

Render a <menu> HTML element.

Parameters:
class html5.elements.Meta(*children, **attributes)

Bases: Element

Render a <meta> HTML element.

Parameters:
class html5.elements.Meter(*children, **attributes)

Bases: Element

Render a <meter> HTML element.

Parameters:
class html5.elements.Nav(*children, **attributes)

Bases: Element

Render a <nav> HTML element.

Parameters:
class html5.elements.Noscript(*children, **attributes)

Bases: Element

Render a <noscript> HTML element.

Parameters:
class html5.elements.Object(*children, **attributes)

Bases: Element

Render a <object> HTML element.

Parameters:
class html5.elements.Ol(*children, **attributes)

Bases: Element

Render a <ol> HTML element.

Parameters:
class html5.elements.Optgroup(*children, **attributes)

Bases: Element

Render a <optgroup> HTML element.

Parameters:
class html5.elements.Option(*children, **attributes)

Bases: Element

Render a <option> HTML element.

Parameters:
class html5.elements.Output(*children, **attributes)

Bases: Element

Render a <output> HTML element.

Parameters:
class html5.elements.P(*children, **attributes)

Bases: Element

Render a <p> HTML element.

Parameters:
class html5.elements.Param(*children, **attributes)

Bases: Element

Render a <param> HTML element.

Parameters:
class html5.elements.Picture(*children, **attributes)

Bases: Element

Render a <picture> HTML element.

Parameters:
class html5.elements.Pre(*children, **attributes)

Bases: Element

Render a <pre> HTML element.

Parameters:
class html5.elements.Progress(*children, **attributes)

Bases: Element

Render a <progress> HTML element.

Parameters:
class html5.elements.Q(*children, **attributes)

Bases: Element

Render a <q> HTML element.

Parameters:
class html5.elements.Rp(*children, **attributes)

Bases: Element

Render a <rp> HTML element.

Parameters:
class html5.elements.Rt(*children, **attributes)

Bases: Element

Render a <rt> HTML element.

Parameters:
class html5.elements.Ruby(*children, **attributes)

Bases: Element

Render a <ruby> HTML element.

Parameters:
class html5.elements.S(*children, **attributes)

Bases: Element

Render a <s> HTML element.

Parameters:
class html5.elements.Samp(*children, **attributes)

Bases: Element

Render a <samp> HTML element.

Parameters:
class html5.elements.Script(*children, **attributes)

Bases: Element

Render a <script> HTML element.

Parameters:
class html5.elements.Section(*children, **attributes)

Bases: Element

Render a <section> HTML element.

Parameters:
class html5.elements.Select(*children, **attributes)

Bases: Element

Render a <select> HTML element.

Parameters:
class html5.elements.Slot(*children, **attributes)

Bases: Element

Render a <slot> HTML element.

Parameters:
class html5.elements.Small(*children, **attributes)

Bases: Element

Render a <small> HTML element.

Parameters:
class html5.elements.Source(*children, **attributes)

Bases: Element

Render a <source> HTML element.

Parameters:
class html5.elements.Span(*children, **attributes)

Bases: Element

Render a <span> HTML element.

Parameters:
class html5.elements.Strong(*children, **attributes)

Bases: Element

Render a <strong> HTML element.

Parameters:
class html5.elements.Style(*children, **attributes)

Bases: Element

Render a <style> HTML element.

Parameters:
class html5.elements.Sub(*children, **attributes)

Bases: Element

Render a <sub> HTML element.

Parameters:
class html5.elements.Summary(*children, **attributes)

Bases: Element

Render a <summary> HTML element.

Parameters:
class html5.elements.Sup(*children, **attributes)

Bases: Element

Render a <sup> HTML element.

Parameters:
class html5.elements.Table(*children, **attributes)

Bases: Element

Render a <table> HTML element.

Parameters:
class html5.elements.Tbody(*children, **attributes)

Bases: Element

Render a <tbody> HTML element.

Parameters:
class html5.elements.Td(*children, **attributes)

Bases: Element

Render a <td> HTML element.

Parameters:
class html5.elements.Template(*children, **attributes)

Bases: Element

Render a <template> HTML element.

Parameters:
class html5.elements.Textarea(*children, **attributes)

Bases: Element

Render a <textarea> HTML element.

Parameters:
class html5.elements.Tfoot(*children, **attributes)

Bases: Element

Render a <tfoot> HTML element.

Parameters:
class html5.elements.Th(*children, **attributes)

Bases: Element

Render a <th> HTML element.

Parameters:
class html5.elements.Thead(*children, **attributes)

Bases: Element

Render a <thead> HTML element.

Parameters:
class html5.elements.Time(*children, **attributes)

Bases: Element

Render a <time> HTML element.

Parameters:
class html5.elements.Title(*children, **attributes)

Bases: Element

Render a <title> HTML element.

Parameters:
class html5.elements.Tr(*children, **attributes)

Bases: Element

Render a <tr> HTML element.

Parameters:
class html5.elements.Track(*children, **attributes)

Bases: Element

Render a <track> HTML element.

Parameters:
class html5.elements.U(*children, **attributes)

Bases: Element

Render a <u> HTML element.

Parameters:
class html5.elements.Ul(*children, **attributes)

Bases: Element

Render a <ul> HTML element.

Parameters:
class html5.elements.Var(*children, **attributes)

Bases: Element

Render a <var> HTML element.

Parameters:
class html5.elements.Video(*children, **attributes)

Bases: Element

Render a <video> HTML element.

Parameters:
class html5.elements.Wbr(*children, **attributes)

Bases: Element

Render a <wbr> HTML element.

Parameters: