Skip to content

Commit

Permalink
Fix style attribute rendering (#44)
Browse files Browse the repository at this point in the history
* Fixes style attribute rendering and adds a test

* Add changelog entry and bump patch version

---------

Co-authored-by: Thomas <thomasborgen91@gmai.com>
  • Loading branch information
thomasborgen and Thomas authored Sep 25, 2024
1 parent f052367 commit 1122a76
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@

## Latest Changes

## Version 5.3.2

* Fixes `style` attribute rendering.

## Version 5.3.1

Expand Down
18 changes: 16 additions & 2 deletions hypermedia/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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 ""
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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 <thomasborgen91@gmail.com>"]
readme = "README.md"
Expand Down
8 changes: 8 additions & 0 deletions tests/attributes/test_styles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from hypermedia import Div


def test_style_renders_correctly() -> None:
assert (
Div(style={"color": "red", "font-size": "10px"}).dump()
== "<div style='color:red;font-size:10px;'></div>"
)

0 comments on commit 1122a76

Please sign in to comment.