From 1122a76cb132b1198333af3bd9dfbb2fb7893634 Mon Sep 17 00:00:00 2001 From: Borgen Date: Wed, 25 Sep 2024 22:02:16 +0300 Subject: [PATCH] Fix style attribute rendering (#44) * Fixes style attribute rendering and adds a test * Add changelog entry and bump patch version --------- Co-authored-by: Thomas --- CHANGELOG.md | 3 +++ hypermedia/models/base.py | 18 ++++++++++++++++-- pyproject.toml | 2 +- tests/attributes/test_styles.py | 8 ++++++++ 4 files changed, 28 insertions(+), 3 deletions(-) create mode 100644 tests/attributes/test_styles.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 693d0ac..1d7ade1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ ## Latest Changes +## Version 5.3.2 + +* Fixes `style` attribute rendering. ## Version 5.3.1 diff --git a/hypermedia/models/base.py b/hypermedia/models/base.py index 9b92658..238c48e 100644 --- a/hypermedia/models/base.py +++ b/hypermedia/models/base.py @@ -16,6 +16,12 @@ FINAL_KEY_PREFIX: Final[str] = "$" +_CUSTOM_RENDERED_ATTRIBUTES: Final[set[str]] = { + "classes", + "class_", + "style", +} + @lru_cache def _load_attribute_aliases() -> Mapping[str, str]: # noqa: C901 @@ -130,8 +136,8 @@ def _render_attributes(self) -> str: # noqa: C901 classes.append(class_) for key, value in self.attributes.items(): - # Skip class attributes that are already handled - if key in ["classes", "class_"]: + # Skip class and style attributes that we handle separately + if key in _CUSTOM_RENDERED_ATTRIBUTES: continue # Skip None values, use `True` for key only values if value is None: @@ -158,6 +164,14 @@ def _render_attributes(self) -> str: # noqa: C901 if len(classes) > 0: result.append(f"class='{' '.join(classes)}'") + if style := self.attributes.get("style", None): + result.append( + "style='{styles}'".format( + styles="".join( + f"{key}:{value};" for key, value in style.items() + ) + ) + ) if result: return " " + " ".join(result) return "" diff --git a/pyproject.toml b/pyproject.toml index 9e64a16..24613d6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "hypermedia" -version = "5.3.1" +version = "5.3.2" description = "An opinionated way to work with html in pure python with htmx support." authors = ["Thomas Borgen "] readme = "README.md" diff --git a/tests/attributes/test_styles.py b/tests/attributes/test_styles.py new file mode 100644 index 0000000..886b1be --- /dev/null +++ b/tests/attributes/test_styles.py @@ -0,0 +1,8 @@ +from hypermedia import Div + + +def test_style_renders_correctly() -> None: + assert ( + Div(style={"color": "red", "font-size": "10px"}).dump() + == "
" + )