https://github.com/tvst/htbuilder
A purely-functional HTML builder for Python. Think JSX rather than templates.
https://github.com/tvst/htbuilder
Last synced: 2 months ago
JSON representation
A purely-functional HTML builder for Python. Think JSX rather than templates.
- Host: GitHub
- URL: https://github.com/tvst/htbuilder
- Owner: tvst
- License: apache-2.0
- Created: 2020-03-27T03:26:02.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2023-09-06T20:20:20.000Z (over 1 year ago)
- Last Synced: 2024-06-11T18:37:48.750Z (10 months ago)
- Language: Python
- Size: 69.3 KB
- Stars: 81
- Watchers: 5
- Forks: 5
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-python-html - tvst/htbuilder - functional HTML builder for Python. Think JSX rather than templates. (Libraries / General HTML Generation)
- awesome-python-html - tvst/htbuilder - functional HTML builder for Python. Think JSX rather than templates. (Libraries / General HTML Generation)
README
# htbuilder — 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](https://github.com/tvst/jsbuilder) which
lets you build JavaScript strings by simply annotating Python functions!)## Installation
Just PIP it!
```py
pip install htbuilder
```## Usage
Just import tags like `div` with `from htbuilder import div`, then call them:
```py
# Import any tag you want from htbuilder, and it just works!
from htbuilder import divdom = div('Hello world!')
```Then you can get the string output by calling `str()` on it:
```py
str(dom)
# Returns 'Hello world!'
```...which means you can also just `print()` to see it in the terminal:
```py
print(dom)
# Prints 'Hello world!'
```To specify attributes, call the tag builder with keyword args:
```py
'
print(
div(id='sidebar', foo='bar')
)
# Prints '
```To specify both attributes and children, you can just use regular Python argument
notation:```py
print(
div("Hello world!", id='sidebar', foo='bar')
)
# Prints 'Hello world!'
```...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:
1. You can then pass the children afterwards **inside a new set of parentheses**:
```py
print(
div(id='sidebar', foo='bar')(
"Hello world!"
)
)
# Prints 'Hello world!'
```1. Or you can pass the children inside `[]` for added clarity:
```py
print(
div(id='sidebar', foo='bar')[
"Hello world!"
]
)
# Prints 'Hello world!'
```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:
```py
from htbuilder import div, ul, li, imgdom = (
div(id='container')[
ul(_class='greetings')[
li('hello'),
li('hi'),
li('whattup'),
]
]
)print(dom)
# Prints this (but without added spacing):
#
#
#- hello
#- hi
#- whattup
#
#
```## Programmatically add children
You can also pass any iterable to specify multiple children, which means you can
simply use things like generator expressions for great awesome:```py
from htbuilder import div, ul, li, imgimage_paths = [
'http://myimages.com/foo1.jpg',
'http://myimages.com/foo2.jpg',
'http://myimages.com/foo3.jpg',
]dom = (
div(id='container')[
ul(_class='image-list')[
li(img(src=image_path, _class='large-image'))
for image_path in image_paths
]
]
)print(dom)
# Prints:
#
#
#
#
#
#
#
```## Conditionally add elements
And because it's just Python, you can use an if/else expression to conditionally
insert elements:```py
use_bold = Truedom = (
div(
b("bold text") if use_bold else "normal text"
)
)print(dom)
# Prints:bold text
```## Modify elements imperatively
Elements accumulate the arguments you send to them, so you can intersperse DOM and code very
naturally:```py
parent = div()for url in img_urls:
child = img(src="https://foo.com/myimage.png")
child.width = 200
child.height = 100if alt_text:
child.alt = alt_text
else:
child.alt = "The developer forgot to enter a description. Go scold them!"parent(child)
```## Styling
We provide helpers to write styles without having to pass huge style strings as
arguments. Instead, just use handy builders like `styles()`, `classes()`,
`fonts()`, along with helpers you can import from the `units` and `funcs`
modules.```py
# styles, classes, and fonts are special imports to help build attribute strings.
from htbuilder import div, styles, classes, fonts# You can import anything from .units and .funcs to make it easier to specify
# units like "%" and "px", as well as functions like "rgba()" and "rgba()".
from htbuilder.units import percent, px
from htbuilder.funcs import rgba, rgbbottom_margin = 10
is_big = Truedom = (
div(
_class=classes('btn', big=is_big)
style=styles(
color='black',
font_family=fonts('Comic Sans', 'sans-serif'),
margin=px(0, 0, bottom_margin, 0),
padding=(px(10), percent(5))
box_shadow=[
(0, 0, px(10), rgba(0, 0, 0, 0.1)),
(0, 0, '2px', rgb(0, 0, 0)),
],
)
)
)# Prints:
#
```## Underscores are magic
### Use underscores instead of dashes
Like most popular languages, Python doesn't support dashes in identifiers. So if you want to build
an element that includes dashes in the tag name or attributes, like ``, you can
do so by using underscores instead:```py
from htbuilder import my_elementdom = my_element(foo_bar="baz")
print(dom)
# Prints:
#
```### Prefix with underscore to avoid reserved words
The word `class` is reserved in Python, so if you want to set an element's `class` attribute you
should prepend it with an underscore like this:```py
dom = div(_class="myclass")print(dom)
# Prints:
#
```This works because underscores preceding or following any identifier are automatically stripped away
for you.