Commits

matthijs committed 52f4dff

Add 'htmlspecialchars' as a "builtin" macro

This allows templates and other code to perform html escaping of strings
where needed. This implements the escaping from scratch, since there is
no useful function for it built into python (there are some modules, but
they either require newer python version or don't escape ").

The name 'htmlspecialchars' was borrowed from PHP, since this function
implements the same behaviour.

  • Participants
  • Parent commits 1c5b5cf

Comments (0)

Files changed (2)

 
     This site has been updated on {{ today() }} by {{ author }}.
 
+#### Builtin macros
+
+Builtin macros can be used from the macros module as well as from python
+code in your pages and templates (just as if they are defined within
+your macros.py).
+
+Currently, there is only one builtin macro available.
+
+`htmlspecialchars(s)`
+
+> Replace the characters that are special within HTML (&, <, > and ")
+> with their equivalent character entity (e.g., &amp;). This should be
+> called whenever an arbitrary string is inserted into HTML (so in most
+> places where you use `{{ variable }}` in your templates).
+>
+> Note that " is not special in most HTML, only within attributes.
+> However, since escaping it does not hurt within normal HTML, it is
+> just escaped unconditionally.
+
 ### Working with pages
 
 Next to stuff defined in `macros.py` the objects `page` and `pages` are
     macros["input"] = dir_in
     macros["output"] = dir_out
 
+    # "builtin" functions for use in macros and templates
+    macros["htmlspecialchars"] = htmlspecialchars
+
     # -------------------------------------------------------------------------
     # process input files
     # -------------------------------------------------------------------------
     return opts
 
 # =============================================================================
+# template helper functions
+# =============================================================================
+def htmlspecialchars(s):
+    """
+    Replace the characters that are special within HTML (&, <, > and ")
+    with their equivalent character entity (e.g., &amp;). This should be
+    called whenever an arbitrary string is inserted into HTML (so in most
+    places where you use {{ variable }} in your templates).
+
+    Note that " is not special in most HTML, only within attributes.
+    However, since escaping it does not hurt within normal HTML, it is
+    just escaped unconditionally.
+    """
+    escape = {
+        "&": "&amp;",
+        '"': "&quot;",
+        ">": "&gt;",
+        "<": "&lt;",
+    }
+
+    # Look up the translation for every character in s (defaulting to
+    # the character itself if no translation is available).
+    return ''.join([escape.get(c,c) for c in s])
+
+# =============================================================================
 # main
 # =============================================================================