Skip to content

Commit

Permalink
Adding support for raw content, and raw tags
Browse files Browse the repository at this point in the history
  • Loading branch information
Zohaib Sibte Hassan committed Dec 26, 2023
1 parent 070beb2 commit 280d003
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,12 @@ async def home(request):
)
)
))
```

## Contributing

I use pytest for testing, and coverage for coverage report. You can simply run tests by:

```sh
coverage run -m pytest && coverage html && open htmlcov/index.html
```
18 changes: 17 additions & 1 deletion htmxido/htmx.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
'br', 'track', 'input',
'col', 'base', 'hr'
}
default_raw = {
'script'
}


def _kebab_case(s: str) -> str:
Expand Down Expand Up @@ -61,6 +64,14 @@ def _flatten(col: Iterable[Any]) -> List[Any]:
return ret


class RawContent:
def __init__(self, _content: str) -> None:
self._content = _content

def __str__(self) -> str:
return self._content


class DOMElement:
def __init__(self, tag: str, pre_processor: [TagPreProcessor]) -> None:
self._tag = tag
Expand Down Expand Up @@ -97,8 +108,10 @@ def __str__(self) -> str:
elif self._content is not None:
ret.append(">")
for c in self._content:
if isinstance(c, DOMElement):
if isinstance(c, DOMElement) or isinstance(c, RawContent):
ret.append(str(c))
elif isinstance(c, str) and self._tag in default_raw:
ret.append(c)
elif isinstance(c, str):
ret.append(escape(c))
else:
Expand All @@ -114,6 +127,9 @@ class DOM:
def __init__(self, pre_processor: [TagPreProcessor]) -> None:
self._pre_processor = pre_processor

def raw(self, content) -> RawContent:
return RawContent(content)

def __getattr__(self, tag: str):
if tag.startswith("__") and tag.endswith("__"):
raise HTMXError("Bad tag", tag)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "htmxido"
version = "0.1.3"
version = "0.2.0"
authors = [
{ name="Zohaib Sibte Hassan", email="zohaibsh@gmail.com" },
]
Expand Down
8 changes: 8 additions & 0 deletions test_htmx.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,14 @@ def test_empty_tag_close():
assert str(domx.script(src="test.js")) == '<script src="test.js"></script>'


def test_script_content_is_default_raw():
assert str(domx.script("window.alert('Hello')")) == "<script>window.alert('Hello')</script>"


def test_explicit_raw():
assert str(domx.div(domx.raw("<Test>"))) == "<div><Test></div>"


class ExceptionTests(unittest.TestCase):
def test_already_added_content_throws(self):
with self.assertRaises(HTMXError) as ctx:
Expand Down

0 comments on commit 280d003

Please sign in to comment.