HTML5Tagger
HTML5Tagger is a Python library designed for Pythonic HTML generation and templating without the need for external template files. It provides a simplified HTML5 syntax, allowing developers to create entire HTML documents using only Python code. Maintained under the Sanic organization, it aims for speed and simplicity, offering a pure Python implementation with no external dependencies. The library sees infrequent but consistent updates, with the latest major release in March 2023.
Warnings
- gotcha Automatic Tag Closing and Empty Elements: Tags are automatically closed when new content or another tag is added. Setting attributes alone does not close an element. For self-closing or empty elements (e.g., `<script src='...'></script>`) where subsequent content should not be nested, explicitly close with `(None)`.
- gotcha Security: Unsafe use of `html5tagger.HTML()` with untrusted input can lead to Cross-Site Scripting (XSS). While content is generally auto-escaped, `html5tagger.HTML(string)` explicitly marks `string` as safe HTML, bypassing escaping.
- gotcha Templating behavior: When using template variables, `doc.TemplateName_` does NOT close the preceding tag but inserts the variable's content *inside* any currently open element. This differs from how new tag calls (`doc.p(...)`) close prior tags.
- deprecated Potential deprecation of non-underscored `_script` and `_style` methods: The introduction of `_script` and `_style` special methods in 2023 suggests a potential future shift to primarily use underscored versions for special element handling, with the non-underscored versions potentially being deprecated or changed.
Install
-
pip install html5tagger
Imports
- Document
from html5tagger import Document
- E
from html5tagger import E
- HTML
from html5tagger import HTML
Quickstart
from html5tagger import Document, E
# Create a full HTML document
doc = Document(
E.TitleText_,
lang="en", # HTML tag attributes as keyword arguments
_urls=["style.css", "script.js"], # Special argument for linking resources
)
# Add elements directly or with context managers
with doc.body:
doc.h1("Welcome to html5tagger!")
with doc.p("This is an example of creating HTML content in Python. It's ") as p:
p.strong("easy")
p(" and ")
p.em("intuitive")
p(".")
# Nesting elements
with doc.ul:
doc.li("No manual closing tags for most elements.")
doc.li("Attributes are passed as keyword arguments.")
doc.li.a(href="https://github.com/sanic-org/html5tagger")("Check out the GitHub repo!")
# Add a paragraph with a dynamic title using template variables
doc.p(doc.IntroText_, id="intro-paragraph")
# Fill in template variables (optional)
doc.TitleText = "My Dynamic Page"
doc.IntroText = "Here's some dynamic content."
# Render the document to an HTML string
html_output = doc.render()
print(html_output)