A small and lazy HTML generator library.
Use Python classes to describe an HTML document, then get a character generator of the rendered output.
All specific element classes derive from either HTMLElement or VoidHTMLElement.
The HTMLElement constructor looks like this:
HTMLElement(self, text=None, children=None, **attrs)where:
textwill be escaped and become the rendered element'sinnerTextvaluechildrenis eitherNone(forvoid-typeelements) or a list of element instances to be rendered as children of this instance**attrsis the element attributes specified as keyword args
Some HTML attribute names are not valid Python keyword names, e.g. class, data-count.
One solution is to pass an unpacked dict:
Div(**{'class': 'fancy', 'data-count': 1})Another solution is to encode the keyword name in a Python-friendly way as described below.
Adding a leading underscore ('_') char to the keyword name signals that the key should be escaped before being rendered to HTML, resulting in:
- the first leading underscore being stripped
- all subsequent underscores being replaced with hyphens
Examples:
- you can specify the HTML attribute
class="fancy"as the keyword arg_class='fancy' - you can specify the HTML attribute
data-count="1"as the keyword arg_data_count=1
from __init__ import (
Body,
Div,
Head,
Html,
Meta,
Title,
)
# Construct your document using element classes.
el = Html(lang='en', children=[
Head(children=[
Meta(charset='utf-8'),
Title('example document'),
]),
Body(children=[
Div('some text', id="id-1", _class="class-1")
])
])
# Get an HTML character generator for the element and its children.
gen = el.html()print([next(gen) for _ in range(5)])['<', 'h', 't', 'm', 'l']print(''.join(gen))<html lang="en">
<head>
<meta charset="utf-8">
<title>
example document
</title>
</head>
<body>
<div id="id-1" class="class-1">
some text
</div>
</body>
</html>from __init__ import (
Div,
Document,
Title,
)
gen = Document(
head_els=[
Title('example document'),
],
body_els=[
Div('some text', id="id-1", _class="class-1")
]
)
print(''.join(gen))<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>
example document
</title>
</head>
<body>
<div id="id-1" class="class-1">
some text
</div>
</body>
</html>