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:
$("#mydiv").append("{{ html_string|escapejs }}");
Django’s |escapejs filter would escape things in html_string (eg quotes, special chars) that could break the intended use of this code block, but Jinja2 does not seem to have an equivalent filter (am I wrong here?).
Is there a cleaner solution than copying/pasting the code from Django?
I faced a similar problem last year. Not sure whether you’re using bottle, but my solution looked something like this.
(I wrapped the
template_settingsdict in a helper function since I used it everywhere, but I kept it simple in this example.)Unfortunately, it’s not as simple as a builtin jinja2 filter, but I was able to live with it happily–especially considering that I had several other custom filters to add, too.
Important Note: Hat tip to @medmunds’s for his astute comment below, reminding us that json.dumps is not XSS-safe. IOW, you wouldn’t want to use it in a production, internet-facing server. Recommendation is to write a safer json escape routine (or steal django’s–sorry OP, I know you were hoping to avoid that) and call that instead of using json.dumps.