diff --git a/kallithea/lib/helpers.py b/kallithea/lib/helpers.py --- a/kallithea/lib/helpers.py +++ b/kallithea/lib/helpers.py @@ -18,6 +18,7 @@ Consists of functions to typically be us available to Controllers. This module is available to both as 'h'. """ import hashlib +import json import StringIO import math import logging @@ -100,6 +101,36 @@ def html_escape(s): .replace("'", "'") ) +def js(value): + """Convert Python value to the corresponding JavaScript representation. + + This is necessary to safely insert arbitrary values into HTML " + is forbidden), the function ensures that the result never contains + '&', '<' and '>', thus making it safe in both those contexts (but + not in attributes). + """ + return literal( + ('(' + json.dumps(value) + ')') + # In JSON, the following can only appear in string literals. + .replace('&', r'\x26') + .replace('<', r'\x3c') + .replace('>', r'\x3e') + ) + def shorter(s, size=20): postfix = '...' if len(s) > size: