From 1fb22c7b6f7338bdae34b2001e4330ae682ac328 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hugo=20H=C3=B6rnquist?= Date: Sun, 6 Aug 2023 22:14:44 +0200 Subject: Allow render of HTML fragment from external module. --- mu4web/html_render.py | 50 ++++++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/mu4web/html_render.py b/mu4web/html_render.py index 1fa8bec..ba7742e 100644 --- a/mu4web/html_render.py +++ b/mu4web/html_render.py @@ -33,7 +33,28 @@ standalones = ['hr', 'br', 'meta'] """Tags which can't have a closing tag.""" -def _render_document(document: HTML) -> str: +def render_fragment(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 + """ if isinstance(document, tuple): tag, *body = document if body and isinstance(body[0], dict): @@ -48,14 +69,14 @@ def _render_document(document: HTML) -> str: return start else: if body: - items = ''.join(_render_document(b) for b in body) + items = ''.join(render_fragment(b) for b in body) else: items = '' return start + f'{items}' elif callable(document): return str(document()) elif isinstance(document, list): - return ''.join(_render_document(e) for e in document) + return ''.join(render_fragment(e) for e in document) elif document is None: return '' else: @@ -65,24 +86,9 @@ def _render_document(document: HTML) -> str: def render_document(document: HTML) -> str: """ - Render an HTML structure to an Html string. + Render a complete HTML document. - 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 + Renders the given root fragment, and prepends a doctype + declaration. """ - return '\n' + _render_document(document) + return '\n' + render_fragment(document) -- cgit v1.2.3