Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions examples/markdown_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import htag
from htag import Tag, App, HTML
import mistune

class MarkdownViewer(Tag.div):
"""
A simple component that renders Markdown text to raw HTML.
It uses the `HTML` string wrapper to prevent `htag` from escaping the rendered HTML.
"""
def __init__(self, markdown_text: str, **kwargs):
super().__init__(**kwargs)

# We process the markdown into an HTML string
rendered_html_string = mistune.html(markdown_text)

# We wrap the result in htag.HTML to mark it as safe, avoiding XSS escapes
# and we append it as a child to our component.
self += HTML(rendered_html_string)

class MarkdownExample(App):
""" Main Application demonstrating the markdown bypass. """
def init(self):
self += Tag.h1("Markdown Render Example")
self += Tag.p("The following block is rendered from markdown:")

# An example of markdown content
md_content = '''
## Hello Markdown!

This is a **bold** statement and this is *italic*.

- Item 1
- Item 2
- Item 3

You can even add code blocks:
```python
print("Hello World")
```
'''

# Apply the markdown viewer component with some CSS styles
self += MarkdownViewer(
markdown_text=md_content,
style="border: 1px solid #ccc; padding: 10px; background-color: #f9f9f9;"
)

if __name__ == "__main__":
import uvicorn
from htag import WebApp

app = WebApp(MarkdownExample)
uvicorn.run(app, host="127.0.0.1", port=8000)
3 changes: 2 additions & 1 deletion htag/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .core import prevent, stop, State, States, current_request
from .core import prevent, stop, State, States, current_request, HTML
from .tag import Tag
from .runner import AppRunner as App
from .web import WebApp
Expand All @@ -20,6 +20,7 @@

__all__ = [
"__version__",
"HTML", # safe string wrapper
"Tag", # the main thing
"State", # State management
"States", # Multi-State management container
Expand Down
11 changes: 11 additions & 0 deletions htag/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@
logger = logging.getLogger("htag")


class HTML(str):
"""
A string subclass to mark HTML code as safe so it is not escaped
when rendered in a GTag.
"""
pass




from .css import _scope_css, _scoped_style_cache

Expand Down Expand Up @@ -883,6 +892,8 @@ def collect(item: Any) -> None:
if stringify:
if isinstance(child, GTag) or (self.tag in ("style", "script")):
return str(child)
if isinstance(child, HTML):
return str(child)
return html.escape(str(child))
return child

Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Repository = "https://github.com/manatlan/htag.git"
[dependency-groups]
dev = [
"httpx>=0.28.1",
"mistune>=3.2.0",
"mkdocs-material>=9.7.1",
"mkdocstrings[python]>=1.0.3",
"mypy>=1.19.1",
Expand Down
25 changes: 25 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -808,3 +808,28 @@ def my_handler(): nonlocal called; called = True
cb = prevent(my_handler)
cb()
assert called is True

def test_html_escape_bypass():
from htag import Tag, HTML

# Standard string is escaped
t = Tag.div("<b>test</b>")
assert "&lt;b&gt;test&lt;/b&gt;" in str(t)
assert "<b>" not in str(t)

# HTML wrapper bypasses escape
t2 = Tag.div(HTML("<b>test</b>"))
assert "<b>test</b>" in str(t2)
assert "&lt;b&gt;" not in str(t2)

# Mix and match via __add__
t3 = Tag.div()
t3 += "<i>hello</i>"
t3 += HTML("<b>world</b>")
assert "&lt;i&gt;hello&lt;/i&gt;" in str(t3)
assert "<b>world</b>" in str(t3)

# Mix and match via childs
t4 = Tag.div(["<i>hello</i>", HTML("<b>world</b>")])
assert "&lt;i&gt;hello&lt;/i&gt;" in str(t4)
assert "<b>world</b>" in str(t4)
16 changes: 15 additions & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading