A purely-functional HTML builder for Python. Think JSX rather than templates.
pip install htbuilderhtbuilder — tiny HTML string builder for Python
htbuilder lets you build HTML strings using a purely functional syntax in Python. Why use templating languages when you can just use functions?
(PS: If you like this, check out jsbuilder which lets you build JavaScript strings by simply annotating Python functions!)
Installation
Just PIP it!
pip install htbuilder
Usage
Just import tags like div with from htbuilder import div, then call them:
# Import any tag you want from htbuilder, and it just works!
from htbuilder import div
dom = div('Hello world!')
Then you can get the string output by calling str() on it:
str(dom)
# Returns '<div>Hello world!</div>'
...which means you can also just print() to see it in the terminal:
print(dom)
# Prints '<div>Hello world!</div>'
To specify attributes, call the tag builder with keyword args:
print(
div(id='sidebar', foo='bar')
)
# Prints '<div id="sidebar" foo="bar"></div>'
To specify both attributes and children, you can just use regular Python argument notation:
print(
div("Hello world!", id='sidebar', foo='bar')
)
# Prints '<div id="sidebar" foo="bar">Hello world!</div>'
...but some might find this order a bit weird! It doesn't the ordering you might be used to in HTML.
So we also support two other notations:
-
You can then pass the children afterwards inside a new set of parentheses:
print( div(id='sidebar', foo='bar')( "Hello world!" ) ) # Prints '<div id="sidebar" foo="bar">Hello world!</div>' -
Or you can pass the children inside
[]for added clarity:print( div(id='sidebar', foo='bar')[ "Hello world!" ] ) # Prints '<div id="sidebar" foo="bar">Hello world!</div>'
All these notations are totally valid and fine! Just pick the one you like best.
Multiple children
Want to output multiple children? Just pass them all as arguments:
from htbuilder import div, ul, li, img
dom = (
div(id='container')[
ul(_class='greetings')[
li('hello'),
li('hi'),
li('whattup'),
]
]
)
print(dom)
# Prints this (but without added spacing):
# <div id="container">
# <ul class="greetings">
# <li>hello</li>
# <li>hi</li>
# <li>whattup</li>
# </ul>
# </div>