When attempting to pass data as JSON from a Flask route to a Jinja template and iterate over it using JavaScript, one might encounter a "SyntaxError: Unexpected token '&'." This error arises when JSON.parse is called on the rendered data.
The issue stems from Flask's Jinja environment, which automatically escapes data rendered in HTML templates as a security measure. When attempting to use this escaped data as JSON in JavaScript, syntax errors occur.
To resolve this issue, Flask provides the tojson filter. This filter automatically dumps the Python data to JSON and marks it safe for rendering in JavaScript.
Example:
return render_template("tree.html", tree=tree)
var tree = {{ tree|tojson }};
Using safe Filter:
If not rendering JSON, the safe filter can be used to prevent Jinja from escaping the data.
Example:
var tree = {{ tree|safe }};
Using Markup:
The data can also be wrapped in Markup before rendering, which is equivalent to using the safe filter.
Example:
var tree = {{ tree }};
If the data is not intended for JavaScript usage but for Jinja, the tojson filter is not required. Pass the Python data directly and use it as any other data in the template.
Example:
return render_template("tree.html", tree=tree)
{% for item in tree %} <li>{{ item }}</li> {% endfor %}
The above is the detailed content of How to Resolve JavaScript's SyntaxError When Parsing Jinja-Rendered JSON Data?. For more information, please follow other related articles on the PHP Chinese website!