Skip to content

DavidVujic/python-hiccup

Repository files navigation

Python Hiccup

Python Hiccup is a library for representing HTML using plain Python data structures.

CircleCI

CodeScene Code Health

Quality Gate Status

What is Python Hiccup?

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.

Usage

Create server side HTML using plain Python data structures. You can also use it with PyScript.

Example

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])

Basic syntax

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>

Resources

Existing python alternatives

Development

Running lint:

uv run ruff check

Running tests:

uv run pytest