'Escaping quotes in jinja2
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
Solution 1:[1]
Jinja2 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 particluar 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 also prevents XSS by escaping important symbols. Tested at on jinja 2.10:
t = jinja2.Template('{{s|tojson}}')
r = t.render(s="</script>...")
print(t) # "\u003c/script\u003e..."
Solution 2:[2]
In flask, there is a default filter called tojson that you could use or, with plain jinja2, you can create your own tojson filter:
>>> import json
>>> env = jinja2.Environment()
>>> env.filters['tojson'] = json.dumps
>>> tmpl = env.from_string("""\
object_name = {
property_name: {{ _(text)|tojson }}
}""")
>>> print tmpl.render({'_': lambda x: x, 'text': 'Some text with "Quotes"'})
object_name = {
property_name: "Some text with \"Quotes\""
}
Solution 3:[3]
didn't understand the question clearly. if escaping with single backslashes didn't work, escape backslashes as well using
object_name = {
property_name: "{{ _(\\\"Some Text which might have \\\"quotes\\\" in it\\\") }}"
}
Solution 4:[4]
If you need to escape HTML in javascript, jinja2 also has the escape filter. This translates &, <, >, ‘, and ” to entities so you can edit html code in a prompt, for instance.
Solution 5:[5]
Filters are applied sequentially so you can do something like this assuming you have your text in the variable sometext:
{{sometext|replace('"',"'")|safe}}
This will apply a replace before marking the string as safe. Remember that you have to trust the source of the string to avoid vulnerabilities.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Garrett |
| Solution 3 | Ajay |
| Solution 4 | FoxyLad |
| Solution 5 | G M |
