diff --git a/htbuilder/__init__.py b/htbuilder/__init__.py index dd50be8..44e87c9 100644 --- a/htbuilder/__init__.py +++ b/htbuilder/__init__.py @@ -53,6 +53,8 @@ from .units import unit from .utils import classes, fonts, rule, styles +from html import escape + EMPTY_ELEMENTS = set( [ # https://developer.mozilla.org/en-US/docs/Glossary/Empty_element @@ -143,13 +145,13 @@ def __getitem__(self, *children: Any): return self(children) def __str__(self) -> str: - children = "".join([str(c) for c in self._children]) + children = "".join([escape(c) if isinstance(c, str) else str(c) for c in self._children]) if self._tag is None: return children tag = _clean_name(self._tag) - attrs = " ".join([f'{_clean_name(k)}="{v}"' for k, v in self._attrs.items()]) + attrs = " ".join([f'{_clean_name(k)}="{escape(str(v))}"' for k, v in self._attrs.items()]) if self._cannot_have_children: if self._attrs: @@ -209,7 +211,12 @@ def _to_flat_list(obj: Any) -> Any: return out +class dont_escape: + def __init__(self, s: str): + self.s = s + def __str__(self): + return self.s + + def __getattr__(tag: str) -> HtmlTag: - if tag == "fragment": return HtmlTag(tag) - return HtmlTag(None)