Escape strings for JavaScript using Jinja2?

前端 未结 6 2198
清酒与你
清酒与你 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:46

    I just researched this problem, my solution is to define a filter:

    from flask import Flask, Markup
    app = Flask(__name__)
    app.jinja_env.filters['json'] = lambda v: Markup(json.dumps(v))
    

    and in the template:

    
    

    This has the nice feature that myvar can be anything that can be JSON-serialised

提交回复
热议问题