Skip to content

DavidVujic/python-hiccup

Repository files navigation

Python Hiccup

This project started out as a fun challenge, and now evolving into something that could be useful.

Current status: experimental

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.

Usage

Create server side HTML using plain Python data structures. This library should also be possible to combine with PyScript, but I haven't tested that out yet.

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

  • Hiccup - the original implementation, for Clojure.

Existing python alternatives