Escape strings for JavaScript using Jinja2?

前端 未结 6 2193
清酒与你
清酒与你 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 15:07

    You can also use jinja2's autoescape. So, for instance, you could add autoescape to your jinja2 Environment in Python:

    JINJA_ENVIRONMENT = jinja2.Environment(
        loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
        autoescape=True)
    

    Alternatively, you could use the Autoescape Extension added in Jinja 2.4 to have more control over where the autoescaping is used in the HTML. More information on this here and example (in Google App Engine) here.

    Python:

    JINJA_ENVIRONMENT = jinja2.Environment(
        loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
        extensions=['jinja2.ext.autoescape'])
    

    HTML:

    {% autoescape true %}
        
            
                {{ IWillBeEscaped }}
            
        
    {% endautoescape %}
    

提交回复
热议问题