Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
161
rated 0 times [  167] [ 6]  / answers: 1 / hits: 25482  / 12 Years ago, sun, september 9, 2012, 12:00:00

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?


More From » python

 Answers
12

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

@app.route('/foo')
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.


[#83170] Friday, September 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mira

Total Points: 460
Total Questions: 108
Total Answers: 99

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
mira questions
;