htbuilder
htbuilder is a Python library for building HTML strings using a purely functional syntax, akin to JSX rather than traditional templating engines. It allows developers to construct HTML elements and attributes using Python functions, providing a clean and programmatic way to generate markup. The library is currently active, with its latest version being 0.9.0, released in September 2023.
Common errors
-
SyntaxError: invalid syntax (when using dash in tag or attribute name)
cause Python does not allow hyphens in variable or function names, which are used to represent HTML tags/attributes in `htbuilder`.fixReplace hyphens with underscores. E.g., `from htbuilder import my_component` instead of `my-component`, and `div(data_attribute='value')` instead of `div(data-attribute='value')`. -
TypeError: __call__() got an unexpected keyword argument 'class'
cause Attempting to use a Python reserved keyword like `class` directly as an HTML attribute name without escaping it.fixPrefix the reserved keyword with an underscore. For `class`, use `_class`. Example: `div(_class='my-css-class')`.
Warnings
- gotcha When defining HTML tag names or attributes that contain dashes (e.g., `my-element`, `foo-bar`), use underscores instead. Python identifiers do not support dashes, and `htbuilder` automatically converts underscores to dashes during rendering.
- gotcha If you need to use a Python reserved keyword (like `class` or `for`) as an HTML attribute name, prefix it with an underscore. `htbuilder` will strip the leading underscore before rendering the HTML.
- gotcha htbuilder is designed for a purely functional approach to HTML generation, similar to JSX. It is not a templating engine like Jinja2 or Django Templates. Expect to write Python code for all HTML structure rather than using string-based templates.
Install
-
pip install htbuilder
Imports
- div
from htbuilder import div
- H
from htbuilder import H
- styles
from htbuilder import styles
- px
from htbuilder.units import px
Quickstart
from htbuilder import div, p, a, H
# Create a simple div with text
hello_world = div('Hello, World!')
print(hello_world.render())
# Expected: <div>Hello, World!</div>
# Create an element with attributes and children
link_element = a(href='https://github.com/tvst/htbuilder')('htbuilder GitHub')
paragraph_element = p('Visit the ', link_element, ' for more info.')
# Nest elements using the H (HtmlElement) factory for common tags
page_content = H.div(id='main-content')(
H.h1('Welcome'),
paragraph_element
)
print(page_content.render())