htpy is a Python library designed for generating HTML in plain Python code, eliminating the need for separate templating languages. It aims to make writing HTML fun and efficient, leveraging Python's features like static typing and debugging. The current version is 25.12.0, and it follows a frequent release cadence, often monthly.
pip install htpyVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates creating a simple HTML page with a head, title, body, heading, and an unordered list dynamically generated from a Python list. The `print(page)` call renders the entire structure to an HTML string.
Use dot notation to separate multiple classes: `div(".foo.bar")`.Ensure generators are consumed only once. If content needs to be rendered multiple times, convert the generator to a list or tuple: `ul[list(li[item] for item in my_list)]`.
To render an element to a string, use `str(element)`. For streaming or iterating over chunks, use `element.iter_chunks()`. The `Renderable` protocol provides a consistent API.
When using ASGI frameworks, leverage `htpy.starlette.HtpyResponse` for returning async-rendered content. Refer to the async documentation for details.
Replace spaces with dots for multiple classes: `div(".class1.class2")` instead of `div(".class1 class2")`.If the content needs to be processed multiple times, ensure the generator is converted to a list or tuple (e.g., `ul[tuple(li[item] for item in items)]`) or recreate the generator for each use.
Use `str(element)` to get the full HTML string, or `element.iter_chunks()` for iterable streaming output.
Add the missing element to your imports: `from htpy import div` (or `from htpy import html, body, div` for multiple elements).