RawHTML and HtmlTag
Group: Media
Description
Two escape hatches for HTML that no component covers. HtmlTag
renders one tag of your choosing around normal Drafter content,
keeping all of Drafter's safety. RawHTML renders a string as
HTML exactly as written, keeping none of it. Prefer the
component catalog first, HtmlTag second, and RawHTML last;
the Embed HTML guide walks the
decision.
Syntax
HtmlTag(tag, content, ...)
RawHTML(html)
Parameters
For HtmlTag:
| Parameter | Type | Default | Meaning |
|---|---|---|---|
tag |
str |
required | The HTML tag name, like "u" or "cite". |
*content |
strings or components | required | Normal Drafter content, escaped and safe as always. |
For RawHTML:
| Parameter | Type | Default | Meaning |
|---|---|---|---|
html |
str |
required | Markup rendered exactly as written, with no escaping. |
Examples
from drafter import *
from dataclasses import dataclass
@dataclass
class State:
pass
@route
def index(state: State) -> Page:
return Page(state, [
Header("Two escape hatches"),
Paragraph(
"HtmlTag wraps safe content: ",
HtmlTag("cite", "The Care and Feeding of Corgis"),
"."
),
RawHTML("<p>RawHTML renders <em>anything</em>, "
"as written.</p>")
])
start_server(State())
Notes
- The safety rule for
RawHTML: never put text a visitor typed inside it. Form values, state that forms filled, and uploaded file contents can all contain HTML, andRawHTMLwould execute it, script tags included. Content you wrote yourself is fine. HtmlTaghas no such risk: its content goes through the same escaping as everything else, so only the tag itself is yours to get right.RawHTMLrenders inside adiv, so it behaves as a block on the page.- Tests match a
RawHTMLby its exact string (assert_has(page, RawHTML("<p>...</p>"))) and cannot see text inside the blob, one more reason components test better. HtmlTagaccepts styling keywords andclasseslike any component; the inside of aRawHTMLcan only be styled with custom CSS.
Related components
- Text and the
inline semantics family: the
components that usually make
HtmlTagunnecessary.
External links
- Embed HTML: the how-to with the full safety discussion.
- Security honestly: why escaping exists.