build: bump version to 0.10.1
refactor: no need for conditional check in __call__
refactor: change how doctype is prepended to html element
simplify your HTML building.
alternative pronunciation for the letter "H"
The haitch
library provides a builder for composing HTML elements together. The element nodes are functional and will only be rendered when invoked.
Why write your HTML in templates when you can do it in Python?
Python 3.8+
Install haitch
using pip:
$ pip install haitch
Import the library like so:
import haitch as H
By importing the root module, you now have access to any element you want:
# Render known `h1` tag.
h1 = H.h1("Hello, world")
print(h1) # <h1>Hello, world</h1>
# Render custom `foo` tag (useful for web components).
foo = H.foo("Hello, world")
print(foo) # <foo>Hello, world!</foo>
Here is a simple example that showcases the advantage of writing HTML in Python. Let's say we want an ordered list of stored org domain emails:
# Fetch emails from data store.
emails = ["jane@aol.com", "bob@example.com", "mark@mail.org", "karen@hr.org"]
# Build an ordered list with org domain emails.
dom = H.ol(class_="email-list")(
H.li(H.a(href=f"mailto:{email}")(email))
for email in sorted(emails)
if email.endswith(".org")
)
print(dom)
# <ol class="email-list">
# <li><a href="mailto:karen@hr.org">karen@hr.org</a></li>
# <li><a href="mailto:mark@mail.org">mark@mail.org</a></li>
# </ol>
The printed output above is prettified for better readability. The actual output is a minified string with no formatting.
Activate your virtual environment where haitch
is installed and run:
$ python -c "help('haitch')"
Inspired by the fantastic htbuilder library as an alternative to template engines. The library met most of my needs, but I really wanted to expand its functionality by leveraging modern Python features like typing. This coincided with my excitement for Hypermedia-Driven Applications (HDAs) with tools like htmx
and alpine
.
While writing HDAs has simplified my application logic, the lack of autocompletion and diagnostics in templates are quite annoying. Therefore, my goal with this package is to make writing HTML as simple and fun as writing normal Python code by writing normal Python code.
The following features will not be supported:
haitch
supports generic elements and attributes. However, I am not going to write the annotations and documentation for them.<col>
element is directly nested inside of a <colgroup>
element or that the span
attribute for the <col>
element is a positive integer.This library adheres to semantic versioning and keeps a changelog.
Intended to help you to integrate haitch
into your application:
haitch
is distributed under the terms of the BSD-3-Clause license.