diff options
Diffstat (limited to '')
-rw-r--r-- | html_render.py | 44 |
1 files changed, 35 insertions, 9 deletions
diff --git a/html_render.py b/html_render.py index 533ae7c..99140ad 100644 --- a/html_render.py +++ b/html_render.py @@ -1,23 +1,24 @@ import html from typing import ( + Callable, TypeAlias, Union, - Callable, - Optional, - cast, ) -HTML: TypeAlias = Union[tuple, list, Callable[[], str], None, - str, int, float] +HTML: TypeAlias = Union[tuple, + list['HTML'], + Callable[[], str], + None, str, int, float] standalones = ['hr', 'br', 'meta'] +"""Tags which can't have a closing tag.""" def _render_document(document: HTML) -> str: - if type(document) == tuple: + if isinstance(document, tuple): tag, *body = document - if body and type(body[0]) == dict: + if body and isinstance(body[0], dict): print(body[0]) attributes = ' '.join(f'{a}="{html.escape(b)}"' for a, b in body[0].items()) @@ -25,14 +26,18 @@ def _render_document(document: HTML) -> str: start = f'<{tag} {attributes}>' else: start = f'<{tag}>' + if tag in standalones: return start else: - items = ''.join(_render_document(b) for b in body) + if body: + items = ''.join(_render_document(b) for b in body) + else: + items = '' return start + f'{items}</{tag}>' elif callable(document): return str(document()) - elif type(document) == list: + elif isinstance(document, list): return ''.join(_render_document(e) for e in document) elif document is None: return '' @@ -42,4 +47,25 @@ def _render_document(document: HTML) -> str: def render_document(document: HTML) -> str: + """ + Render an HTML structure to an Html string. + + The following Python types are converted as follows: + - Tuples + - The first value becomes the tags name + - The second value, if a dictionary, becomes the tags attributes + - All following values (including the second if not a dictionary) + gets individually passed to render_document. + - Lists + Each element gets passed to render_document + - Callable[[], str] + Gets called, and its output is included verbatim. Useful for + including strings which shouldn't be escaped. + - str + Gets escaped, and included + - int, float + Gets included as their default string representation. + - None + Becomes an empty string + """ return '<!doctype html>\n' + _render_document(document) |