How do I escape HTML with Jinja2 so that it can be used as a string in JavaScript (jQuery)?
If I were using Django\'s templating system I could write:
$(
Based on @tometzky here is my Python 3 version:
_js_escapes = {
'\\': '\\u005C',
'\'': '\\u0027',
'"': '\\u0022',
'>': '\\u003E',
'<': '\\u003C',
'&': '\\u0026',
'=': '\\u003D',
'-': '\\u002D',
';': '\\u003B',
u'\u2028': '\\u2028',
u'\u2029': '\\u2029'
}
# Escape every ASCII character with a value less than 32.
_js_escapes.update(('%c' % z, '\\u%04X' % z) for z in range(32))
@register.filter
def escapejs(value):
return jinja2.Markup("".join(_js_escapes.get(l, l) for l in value))
The usage is exactly the same.