Dominate
Dominate is a Python library (current version 2.9.1) for creating and manipulating HTML documents using an elegant DOM API. It allows developers to write HTML pages concisely in pure Python, eliminating the need for a separate template language. The library is actively maintained with a regular release cadence.
Warnings
- gotcha Newline characters (`\n`) in Python strings are not automatically converted to HTML `<br>` tags when inserted into Dominate elements. You must explicitly add `<br/>` tags or use `dominate.util.text` if you intend for newlines to be preserved visually in the rendered HTML, or `p` tags for paragraphs.
- gotcha When adding attributes to HTML tags, Python keywords (e.g., `class`, `for`) must be escaped with an underscore, like `_class='my-class'` or `_for='my-label'` to avoid syntax errors.
- breaking Version 2.9.1 introduced support for `dominate` to work in async contexts. While this is an enhancement, improper use of `dominate` elements or context managers within `async` functions without awaiting where necessary could lead to unexpected behavior or runtime errors in `asyncio` applications.
- gotcha When reusing tag instances (e.g., creating a tag and then adding content to it multiple times in different contexts), be aware of Dominate's context management. If a tag instance is created outside a `with` block and then used inside multiple `with` blocks, its content might be duplicated or not appear where expected.
Install
-
pip install dominate
Imports
- document
from dominate.document import document
- tags
from dominate import tags
- html
from dominate.tags import html, body, h1
- text
from dominate.util import text
Quickstart
from dominate.document import document
from dominate.tags import html, head, body, h1, p, a, div, br
from dominate.util import text
doc = document(title='My Awesome Page')
with doc.head:
a(href='https://example.com', _class='link-style', data_info='example') << 'Example Link'
with doc.body:
h1('Hello, Dominate!')
p('This is a paragraph created with Python.')
with div(id='container'):
p('Another paragraph inside a div.')
p('Line one.')
br()
p('Line two with explicit break.')
p('Raw text with newline:\n')
text('This text should appear on a new line after the explicit break.')
# Render the document to an HTML string
html_output = doc.render()
print(html_output)
# Example of rendering with pretty printing off
# print(doc.render(pretty=False))