htpy - HTML in Python
Maintained. Last release 6 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity.
pip install htpy
htpy - HTML in Python
htpy is a library that makes writing HTML in plain Python fun and efficient, without a template language.
Define HTML in Python:
from htpy import body, h1, head, html, li, title, ul
menu = ["egg+bacon", "bacon+spam", "eggs+spam"]
print(
html[
head[title["Today's menu"]],
body[
h1["Menu"],
ul(".menu")[(li[item] for item in menu)],
],
]
)
And Get HTML:
<!DOCTYPE html>
<html>
<head>
<title>Today's menu</title>
</head>
<body>
<h1>Menu</h1>
<ul class="menu">
<li>egg+bacon</li>
<li>bacon+spam</li>
<li>eggs+spam</li>
</ul>
</body>
</html>
Motivation for This Project
At Personalkollen, where htpy was originally developed we often found ourselves hitting walls when using classic templates. htpy was created to improve the productiveness and experience of generating HTML from a Python backend.
Key Features
-
Leverage static types: Use mypy or pyright to type check your code.
-
Great debugging: Avoid cryptic stack traces from templates. Use your favorite Python debugger.
-
Easy to extend: There is no special way to define template tags/filters. Just call regular functions.
-
Works with existing Python web framework: Works great with Django, Flask or any other Python web framework!
-
Full async support: Render HTML fully async with ASGI frameworks such as Starlette and FastAPI.
-
Works great with htmx: htpy makes for a great experience when writing server rendered partials/components.
-
Create reusable components: Define components, snippets, complex layouts/pages as regular Python variables or functions.
-
Familiar concepts from React: React helped make it popular writing HTML with a programming language. htpy uses a lot of similar constructs.