Skip to content

Commit

Permalink
Add render_orphans() to render elements without parents.
Browse files Browse the repository at this point in the history
Fixes #22.
  • Loading branch information
pelme committed Jun 25, 2024
1 parent 9221b97 commit 80bb52c
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
13 changes: 13 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,19 @@ snippets as attributes:
<ul data-li-template="&lt;li class=&#34;bar&#34;&gt;&lt;/li&gt;"></ul>
```

## 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"]]))
<tr>a</tr><tr>b</tr>
```

## Iterating of the Output

Iterating over a htpy element will yield the resulting contents in chunks as
Expand Down
4 changes: 4 additions & 0 deletions htpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "".join(_iter_children(orhpans))


class _HasHtml(Protocol):
def __html__(self) -> str: ...

Expand Down
7 changes: 7 additions & 0 deletions tests/test_render_orphans.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from htpy import render_orphans, tr


def test_render_orphan() -> None:
result = render_orphans([tr["a"], tr["b"]])

assert result == "<tr>a</tr><tr>b</tr>"

0 comments on commit 80bb52c

Please sign in to comment.