Flask's Jinja environment automatically escapes data rendered in HTML templates to prevent security issues. When passing Python objects to be treated as JSON, it's essential to handle this escaping correctly to avoid syntax errors in JavaScript.
To render Python objects as safe JSON, use the tojson filter:
return render_template('tree.html', tree=tree)
In the template, use:
var tree = {{ tree|tojson }};
This safely dumps the data to JSON and marks it as safe to prevent escaping.
If the JSON has already been dumped to a string, use the safe filter to mark it as safe for rendering:
return render_template('tree.html', tree=json.dumps(tree))
In the template, use:
var tree = {{ tree|safe }};
Alternatively, you can wrap the string in Markup before rendering:
return render_template('tree.html', tree=Markup(json.dumps(tree)))
In the template, you can use the value as:
var tree = {{ tree }};
If you're using the data in Jinja instead of passing it to JavaScript, don't use tojson. Instead, pass the Python data directly and use it normally in the template:
return render_template('tree.html', tree=tree)
{% for item in tree %} <li>{{ item }}</li> {% endfor %}
The above is the detailed content of How to Avoid JavaScript SyntaxErrors When Using Jinja Templates and JSON Data?. For more information, please follow other related articles on the PHP Chinese website!