########################## Escape and unescape text ########################## Escape text for HTML output and reverse it with :func:`turbohtml.escape` and :func:`turbohtml.unescape` -- the standard library's behavior, byte for byte, several times faster. *************************************** Escape untrusted text for HTML output *************************************** When you interpolate user-supplied text into HTML, escape it first so it cannot break out of its context: .. testcode:: import turbohtml comment = '' print(f"

{turbohtml.escape(comment)}

") .. testoutput::

<script>alert("xss")</script>

************************************************ Escape for a text node without touching quotes ************************************************ Inside element text (not an attribute) the quote characters are safe, so pass ``quote=False`` to leave them untouched and keep the output smaller: .. testcode:: print(turbohtml.escape('He said "hi" & left', quote=False)) .. testoutput:: He said "hi" & left **************************************** Build safe HTML strings for a template **************************************** When you assemble HTML from a mix of trusted markup and untrusted values, use :mod:`turbohtml.migration.markupsafe`. Wrapping a value in :class:`~turbohtml.migration.markupsafe.Markup` declares it safe; combining it with plain text escapes that text, so a forgotten escape cannot inject markup. It is a drop-in for `markupsafe `_, so a `Jinja2 `_ project migrates by changing the import: .. testcode:: from turbohtml.migration.markupsafe import Markup, escape user = "" row = Markup("
  • {}
  • ").format(user) print(row) print(Markup(", ").join(["", escape("a & b")])) .. testoutput::
  • <script>alert(1)</script>
  • <b>, a & b ********************************** Decode HTML character references ********************************** Convert named and numeric references from scraped or stored HTML back into text: .. testcode:: print(turbohtml.unescape("£10 © 🎉")) .. testoutput:: £10 © 🎉 Unescaping follows the HTML5 rules, including longest-match for references that omit the trailing semicolon: .. testcode:: print(turbohtml.unescape("¬it;")) .. testoutput:: ¬it;