From 0ae972784258a2e3e8958fa51f5d513711ebec1c Mon Sep 17 00:00:00 2001 From: Andreas Pelme Date: Sun, 23 Jun 2024 23:07:40 +0200 Subject: [PATCH] Clarify escaping of attributes in the docs. Closes 21. --- docs/usage.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/docs/usage.md b/docs/usage.md index 45a525f..3e4b247 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -261,6 +261,35 @@ Attributes via id/class shorthand, keyword arguments and dictionary can be combi ``` +### Escaping of Attributes + +Attributes are always escaped. This makes it possible to pass arbitrary HTML +fragments or scripts as attributes. The output may look a bit obfuscated since +all unsafe characters are escaped but the browser will interpret it correctly: + +```pycon +>>> from htpy import button +>>> print(button(id="example", onclick="let name = 'andreas'; alert('hi' + name);")["Say hi"]) + +``` + +In the browser, the parsed attribute as returned by +`document.getElementById("example").getAttribute("onclick")` will be the +original string `let name = 'andreas'; alert('hi' + name);`. + +Escaping will happen whether or not the value is wrapped in `markupsafe.Markup` +or not. This may seem confusing at first but is useful when embedding HTML +snippets as attributes: + +```pycon title="Escaping of Markup" +>>> from htpy import ul +>>> from markupsafe import Markup +>>> # This markup may come from another library/template engine +>>> some_markup = Markup("""
  • """) +>>> print(ul(data_li_template=some_markup)) + +``` + ## Iterating of the Output Iterating over a htpy element will yield the resulting contents in chunks as