Render string in Jinja to JavaScript variable
- javascript
- flask
- jinja
- json
Jinja renders Python strings without the quotes. The user tries var x = {{ 'value' }}
and that renders as var x = value
. Whatever value
is, it isn’t valid when JavaScript runs it, so the user sees a weird value or gets an error, rather than the string they expected.
Using {{ value|tojson }}
produces a JSON string, and since the outer quotes are removed when Jinja renders it, it becomes valid JavaScript with the corect type.