Skip to content

Commit 37a2a73

Browse files
Strip whitespace around id and class values in css selector (#100)
* Add tests for parsing id/class css string * Strip whitespace from parsed id/class values * Move tests to `test_attributes.py` * Add note to changelog
1 parent 2181290 commit 37a2a73

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

docs/changelog.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
# Changelog
22

3+
## Next (minor)
4+
- Strip whitespace around id and class values in CSS selector. Fixes
5+
[issue #97](https://github.com/pelme/htpy/issues/97). See [PR #100](https://github.com/pelme/htpy/pull/100).
6+
Thanks to [William Jackson](https://github.com/williamjacksn).
7+
38
## 25.3.0 - 2025-03-16
49
- Add `fragment` for explicitly grouping a collection of nodes. [Read the Usage docs for more details](usage.md#fragments) Fixes
510
[issue #82](https://github.com/pelme/htpy/issues/82).

htpy/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ def _id_class_names_from_css_str(x: t.Any) -> Mapping[str, Attribute]:
6060
raise ValueError("id/class strings must start with # or .")
6161

6262
parts = x.split(".")
63-
ids = [part.removeprefix("#") for part in parts if part.startswith("#")]
64-
classes = [part for part in parts if not part.startswith("#") if part]
63+
ids = [part.removeprefix("#").strip() for part in parts if part.startswith("#")]
64+
classes = [part.strip() for part in parts if not part.startswith("#") if part]
6565

6666
assert len(ids) in (0, 1)
6767

tests/test_attributes.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,21 @@ def test_id_class_only_classes(render: RenderFixture) -> None:
161161
assert render(result) == ['<div class="foo bar">', "</div>"]
162162

163163

164+
def test_id_class_spaces_only_id(render: RenderFixture) -> None:
165+
result = div("#a ")
166+
assert render(result) == ['<div id="a">', "</div>"]
167+
168+
169+
def test_id_class_spaces_only_classes(render: RenderFixture) -> None:
170+
result = div(".a ")
171+
assert render(result) == ['<div class="a">', "</div>"]
172+
173+
174+
def test_id_class_spaces(render: RenderFixture) -> None:
175+
result = div("#a .a ")
176+
assert render(result) == ['<div id="a" class="a">', "</div>"]
177+
178+
164179
def test_id_class_wrong_order() -> None:
165180
with pytest.raises(ValueError, match="id \\(#\\) must be specified before classes \\(\\.\\)"):
166181
div(".myclass#myid")

0 commit comments

Comments
 (0)