Escape strings for JavaScript using Jinja2?

前端 未结 6 2197
清酒与你
清酒与你 2021-02-18 14:10

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:

$(         


        
6条回答
  •  太阳男子
    2021-02-18 14:54

    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.

提交回复
热议问题