meshy meshy - 9 months ago 135
Javascript Question

Escape strings for JavaScript using Jinja2?

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 }}");

would escape things in
(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?

Answer Source

I faced a similar problem last year. Not sure whether you're using bottle, but my solution looked something like this.

import json

def escapejs(val):
    return json.dumps(str(val)) # *but see [Important Note] below to be safe

def foo():
    return bottle.jinja2_template('foo', template_settings={'filters': {'escapejs': escapejs}})

(I wrapped the template_settings dict 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.