From f3c1dc472ed570118cbb88915202bbb99760d3d9 Mon Sep 17 00:00:00 2001 From: Andreas Pelme Date: Tue, 25 Jun 2024 22:14:21 +0200 Subject: [PATCH] Add render_orphans() to render elements without parents. Fixes #22. --- docs/usage.md | 13 +++++++++++++ htpy/__init__.py | 4 ++++ tests/test_render_orphans.py | 10 ++++++++++ 3 files changed, 27 insertions(+) create mode 100644 tests/test_render_orphans.py diff --git a/docs/usage.md b/docs/usage.md index 3e4b247..dcbed02 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -290,6 +290,19 @@ snippets as attributes: ``` +## Render elements without a parent (orphans) + +In some cases such as returning partial content it is useful to render elements +without a parent element. This is useful in HTMX partial responses. + +You may use `render_orphans` to achieve this: + +```pycon title="Render orphan elements without a parent" +>>> from htpy import render_orphans, tr +>>> print(render_orphans([tr["a"], tr["b"]])) +ab +``` + ## Iterating of the Output Iterating over a htpy element will yield the resulting contents in chunks as diff --git a/htpy/__init__.py b/htpy/__init__.py index 615821f..853b3c1 100644 --- a/htpy/__init__.py +++ b/htpy/__init__.py @@ -217,6 +217,10 @@ def __iter__(self) -> Iterator[str]: yield f"<{self._name}{_attrs_string(self._attrs)}>" +def render_orphans(orhpans: Iterable[BaseElement]) -> _Markup: + return _Markup("".join(_iter_children(orhpans))) + + class _HasHtml(Protocol): def __html__(self) -> str: ... diff --git a/tests/test_render_orphans.py b/tests/test_render_orphans.py new file mode 100644 index 0000000..8405492 --- /dev/null +++ b/tests/test_render_orphans.py @@ -0,0 +1,10 @@ +from markupsafe import Markup + +from htpy import render_orphans, tr + + +def test_render_orphan() -> None: + result = render_orphans([tr["a"], tr["b"]]) + + assert isinstance(result, Markup) + assert result == "ab"