Skip to content

Commit 71f3169

Browse files
committed
fix: preserve double underscores in attribute names
Replace blanket replace("_", "-") with a sentinel-based approach that preserves __ in attribute names. This fixes compatibility with frameworks like Datastar that use __ as a modifier delimiter (e.g. data-on:click__debounce.300ms, data-on:submit__prevent).
1 parent a8e16c4 commit 71f3169

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

src/htpy/_elements.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,11 @@ def _python_to_html_name(name: str) -> str:
194194
name_without_underscore_suffix = name.removesuffix("_")
195195
if keyword.iskeyword(name_without_underscore_suffix):
196196
html_name = name_without_underscore_suffix
197-
html_name = html_name.replace("_", "-")
197+
198+
# Preserve double underscores while converting single underscores to
199+
# hyphens. This is needed for frameworks like Datastar that use __ as a
200+
# modifier delimiter in attribute names (e.g. data-on-click__window).
201+
html_name = html_name.replace("__", "\x00").replace("_", "-").replace("\x00", "__")
198202

199203
return html_name
200204

tests/test_attributes.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,14 @@ def test_underscore_replacement(render: RenderFixture) -> None:
103103
assert render(result) == ['<button hx-post="/foo">', "click me!", "</button>"]
104104

105105

106+
def test_double_underscore_preserved(render: RenderFixture) -> None:
107+
# Double underscores should be preserved in attribute names. This is needed
108+
# for frameworks like Datastar that use __ as a modifier delimiter
109+
# (e.g. data-on-click__window).
110+
result = div(data_on_click__window="alert()")
111+
assert render(result) == ['<div data-on-click__window="alert()">', "</div>"]
112+
113+
106114
class Test_attribute_escape:
107115
pytestmark = pytest.mark.parametrize(
108116
"x",

0 commit comments

Comments
 (0)