Python Hiccup is a library for representing HTML using plain Python data structures.
This is a Python implementation of the Hiccup syntax. Python Hiccup is a library for representing HTML in Python.
Using list or tuple to represent HTML elements, and dict to represent the element attributes.
This project started out as a fun coding challenge, and now evolving into something useful for Python Dev teams.
Create server side HTML using plain Python data structures. You can also use it with PyScript.
Python:
from python_hiccup.html import render
render(["div", "Hello world!"])The output will be a string: <div>Hello world!</div>
With Hiccup, you can create HTML in a programmatic style. To render HTML like:
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>with Python:
def todo(data: list) -> list:
return [["li", i] for i in data]
data = todo(["one", "two", "three"])
render(["ul", data])Python:
["div", "Hello world!"]The HTML equivalent is:
<div>Hello world!</div>Writing a nested HTML structure, using Python Hiccup:
["div", ["span", ["strong", "Hello world!"]]]The HTML equivalent is:
<div>
<span>
<strong>Hello world!</strong>
</span>
</div>Adding attributes to an element, such as CSS id and classes, using Python Hiccup:
["div", {"id": "foo", "class": "bar"}, "Hello world!"]or, using a more concise syntax:
["div#foo.bar", "Hello world!"]The HTML equivalent is:
<div id="foo" class="bar">Hello world!</div>Adding valueless attributes to elements, such as the async or defer, by using Python set:
["!DOCTYPE", {"html"}]
["script", {"async"}, {"src": "js/script.js"}]The HTML equivalent is:
<!DOCTYPE html>
<script async src="js/script.js"></script>This is useful when rendering HTML entities like ©.
from python_hiccup.html import raw
data = ["div", raw("© this should <strong>not</strong> be escaped!")]The HTML output:
<div>© this should <strong>not</strong> be escaped!</div>- PyScript and python-hiccup example - PyScript Jokes with a Hiccup
- Hiccup - the original implementation, for Clojure.
Running lint:
uv run ruff checkRunning tests:
uv run pytest