Problem: When attempting to parse JSON data rendered in a Jinja HTML template using JavaScript, a SyntaxError is encountered, indicating an unexpected '&' token.
Cause: Flask's Jinja environment automatically escapes data rendered in HTML templates for security reasons. This is problematic when passing JSON objects to JavaScript, as the escaped characters interfere with parsing.
Solution: Use Flask's tojson Filter or Markup to Mark Data as Safe
To resolve this issue, utilize Flask's tojson filter, which dumps data into JSON and marks it safe for rendering within JavaScript.
return render_template("template.html", data=tree|tojson)
Alternative Approaches:
var data = {{ tree|safe }};
return render_template("template.html", data=Markup(json.dumps(tree)))
Direct Python Data Usage:
If the rendered data is not intended for JavaScript, consider passing the Python data directly without using JSON conversion or filters.
return render_template("template.html", data=tree)
Implementation:
In the Jinja template:
var data = {{ data }}; for (i in obj) { document.write(obj[i].text + "<br />"); }
Alternatively, Jinja data can be utilized directly without JavaScript parsing:
{% for item in tree %} <li>{{ item }}</li> {% endfor %}
The above is the detailed content of How to Fix JavaScript SyntaxErrors When Parsing Jinja-Rendered JSON Data?. For more information, please follow other related articles on the PHP Chinese website!