Skip to content

Strip whitespace around id and class values in css selector #100

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## Next (minor)
- Strip whitespace around id and class values in CSS selector. Fixes
[issue #97](https://github.com/pelme/htpy/issues/97). See [PR #100](https://github.com/pelme/htpy/pull/100).
Thanks to [William Jackson](https://github.com/williamjacksn).

## 25.3.0 - 2025-03-16
- Add `fragment` for explicitly grouping a collection of nodes. [Read the Usage docs for more details](usage.md#fragments) Fixes
[issue #82](https://github.com/pelme/htpy/issues/82).
Expand Down
4 changes: 2 additions & 2 deletions htpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ def _id_class_names_from_css_str(x: t.Any) -> Mapping[str, Attribute]:
raise ValueError("id/class strings must start with # or .")

parts = x.split(".")
ids = [part.removeprefix("#") for part in parts if part.startswith("#")]
classes = [part for part in parts if not part.startswith("#") if part]
ids = [part.removeprefix("#").strip() for part in parts if part.startswith("#")]
classes = [part.strip() for part in parts if not part.startswith("#") if part]

assert len(ids) in (0, 1)

Expand Down
15 changes: 15 additions & 0 deletions tests/test_attributes.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,21 @@ def test_id_class_only_classes(render: RenderFixture) -> None:
assert render(result) == ['<div class="foo bar">', "</div>"]


def test_id_class_spaces_only_id(render: RenderFixture) -> None:
result = div("#a ")
assert render(result) == ['<div id="a">', "</div>"]


def test_id_class_spaces_only_classes(render: RenderFixture) -> None:
result = div(".a ")
assert render(result) == ['<div class="a">', "</div>"]


def test_id_class_spaces(render: RenderFixture) -> None:
result = div("#a .a ")
assert render(result) == ['<div id="a" class="a">', "</div>"]


def test_id_class_wrong_order() -> None:
with pytest.raises(ValueError, match="id \\(#\\) must be specified before classes \\(\\.\\)"):
div(".myclass#myid")
Expand Down