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:
$(
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 %}