Escaping quotes in jinja2
jinja2, python
Solution
Jinja2 starting from version 2.9 has nice filter tojson. If you make json from string, it will generate string enclosed in double quotes "". You can safely use it in javascript. And you don't need put quotes around by yourself.
string = {{ html_string|tojson }};
In your particular case it might be easier to create dict in Python and then convert it to javascript object with single use of
jsObject = {{ py_dict|tojson }};
`tojson` escapes quotes `"` and also prevents XSS by escaping important symbols like `<>&'`. Tested at on jinja 2.10:
t = jinja2.Template('{{s|tojson}}')
r = t.render(s="""</script>"...'""")
print(r) # "\u003c/script\u003e\"...\u0027"
Problem
I am building a json object in jinja file: ``` object_name = { property_name: "{{ _("Some Text which might have "quotes" in it") }}" } ``` And then import the above jinja2 file in a script tag note: _("Text") is used to be replaced by a translation text, so the text in the () will be replaced with text of another language so i can not predict if the translation will contain double quotes any idea how to escape the incoming quotes and convert them to for example " Edited The solution: The solution to this problem for us was by making python go through all the translations and escape all qoutations. but we always have to make sure at least the english text not to be problematic and anyway we have controll over this.... so far :) Look at this document aswell http://pology.nedohodnik.net/doc/user/en_US/ch-poformat.html#sec-poescapes