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 f3c1dc4
Show file tree
Hide file tree
Showing 3 changed files with 27 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 _Markup("".join(_iter_children(orhpans)))


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

Expand Down
10 changes: 10 additions & 0 deletions tests/test_render_orphans.py
Original file line number Diff line number Diff line change
@@ -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 == "<tr>a</tr><tr>b</tr>"

0 comments on commit f3c1dc4

Please sign in to comment.