diff options
Diffstat (limited to '')
-rw-r--r-- | html_render.py | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/html_render.py b/html_render.py new file mode 100644 index 0000000..533ae7c --- /dev/null +++ b/html_render.py @@ -0,0 +1,45 @@ +import html +from typing import ( + TypeAlias, + Union, + Callable, + Optional, + cast, +) + +HTML: TypeAlias = Union[tuple, list, Callable[[], str], None, + str, int, float] + + +standalones = ['hr', 'br', 'meta'] + + +def _render_document(document: HTML) -> str: + if type(document) == tuple: + tag, *body = document + if body and type(body[0]) == dict: + print(body[0]) + attributes = ' '.join(f'{a}="{html.escape(b)}"' + for a, b in body[0].items()) + body = body[1:] + start = f'<{tag} {attributes}>' + else: + start = f'<{tag}>' + if tag in standalones: + return start + else: + items = ''.join(_render_document(b) for b in body) + return start + f'{items}</{tag}>' + elif callable(document): + return str(document()) + elif type(document) == list: + return ''.join(_render_document(e) for e in document) + elif document is None: + return '' + else: + # strings, and everything else + return html.escape(str(document)) + + +def render_document(document: HTML) -> str: + return '<!doctype html>\n' + _render_document(document) |