From 280d003d52d2021a0b7022f67080b30fb58b4125 Mon Sep 17 00:00:00 2001 From: Zohaib Sibte Hassan Date: Mon, 25 Dec 2023 22:44:18 -0800 Subject: [PATCH] Adding support for raw content, and raw tags --- README.md | 8 ++++++++ htmxido/htmx.py | 18 +++++++++++++++++- pyproject.toml | 2 +- test_htmx.py | 8 ++++++++ 4 files changed, 34 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 564eb98..e044589 100644 --- a/README.md +++ b/README.md @@ -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 ``` \ No newline at end of file diff --git a/htmxido/htmx.py b/htmxido/htmx.py index 70cd5ca..1a6a4f6 100644 --- a/htmxido/htmx.py +++ b/htmxido/htmx.py @@ -16,6 +16,9 @@ 'br', 'track', 'input', 'col', 'base', 'hr' } +default_raw = { + 'script' +} def _kebab_case(s: str) -> str: @@ -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 @@ -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: @@ -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) diff --git a/pyproject.toml b/pyproject.toml index 78f8773..93c6fb8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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" }, ] diff --git a/test_htmx.py b/test_htmx.py index 28ca2fb..516153d 100644 --- a/test_htmx.py +++ b/test_htmx.py @@ -70,6 +70,14 @@ def test_empty_tag_close(): assert str(domx.script(src="test.js")) == '' +def test_script_content_is_default_raw(): + assert str(domx.script("window.alert('Hello')")) == "" + + +def test_explicit_raw(): + assert str(domx.div(domx.raw(""))) == "
" + + class ExceptionTests(unittest.TestCase): def test_already_added_content_throws(self): with self.assertRaises(HTMXError) as ctx: