Yattag
Yattag is a Python library for generating HTML or XML in a pythonic way. It offers a pure Python alternative to web template engines, allowing developers to create dynamic HTML documents programmatically. A notable feature is its ability to fill HTML forms with default values and error messages. The current stable version is 1.16.1, released on November 2, 2024, with an active but irregular release cadence.
Warnings
- gotcha When setting HTML `class` attributes, use `klass` as the keyword argument in Python to avoid conflicts with the `class` reserved keyword.
- gotcha For HTML/XML attributes containing hyphens (e.g., `data-id`, `ng-app`), pass them as `(key, value)` tuples because Python keyword arguments cannot contain hyphens.
- gotcha The `text()` method automatically escapes HTML special characters (`&`, `<`, `>`, etc.). If you need to insert raw HTML or XML content without escaping, use the `asis()` method.
- gotcha By default, `doc.getvalue()` returns a compact, non-indented string. This is efficient but can be unreadable. To get human-readable, indented output, use the `indent` function.
Install
-
pip install yattag
Imports
- Doc
from yattag import Doc
- tag, text
from yattag import Doc; doc, tag, text = Doc().tagtext()
- indent
from yattag import indent
Quickstart
from yattag import Doc
doc, tag, text = Doc().tagtext()
with tag('html'):
with tag('head'):
with tag('title'):
text('My Yattag Page')
with tag('body', id='main-body', klass='container'):
with tag('h1'):
text('Hello Yattag World!')
with tag('p'):
text('This is a paragraph generated programmatically.')
result_html = doc.getvalue()
print(result_html)
# To get indented output for readability:
from yattag import indent
indented_html = indent(result_html)
print('\n--- Indented HTML ---')
print(indented_html)