Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping quotes in jinja2

Tags:

python

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

like image 989
Razmig Avatar asked Jul 30 '13 07:07

Razmig


2 Answers

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\""
}
like image 66
Garrett Avatar answered Sep 17 '22 03:09

Garrett


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..."
like image 39
Alexander C Avatar answered Sep 18 '22 03:09

Alexander C