Home >Web Front-end >JS Tutorial >Why Does My JavaScript Get a SyntaxError When Rendering JSON Data from a Jinja Template?

Why Does My JavaScript Get a SyntaxError When Rendering JSON Data from a Jinja Template?

Susan Sarandon
Susan SarandonOriginal
2024-12-11 21:37:10358browse

Why Does My JavaScript Get a SyntaxError When Rendering JSON Data from a Jinja Template?

JavaScript Raises SyntaxError with Data Rendered in Jinja Template

Introduction

When passing JSON data from a Flask route to a Jinja template, the browser may throw a SyntaxError: Unexpected token '&'. Expected a property name when rendering the data. Understanding how to handle rendered JSON data in JavaScript is crucial for successful template handling.

Escaping and JSON Rendering

Flask's Jinja environment automatically escapes data rendered in HTML templates to prevent security vulnerabilities. For data that needs to be treated as JSON, Flask provides the tojson filter, which dumps the data to JSON and marks it as safe. Using the tojson filter ensures that the data is rendered without escaping, allowing it to be parsed correctly in JavaScript.

tree = get_nodes("Root")
return render_template("folder.html", data=tree|tojson)
var tree = {{ tree|tojson }};

Alternatively, in older Flask versions, the safe filter can be used to mark the data as safe:

var tree = {{ tree|tojson|safe }};

Using Safe Filters

If the data has already been dumped to JSON, the safe filter can be used to mark it as safe for rendering without escaping:

return render_template('tree.html', tree=json.dumps(tree))
var tree = {{ tree|safe }};

Wrapping the JSON string in Markup is also equivalent to using the safe filter:

return render_template('tree.html', tree=Markup(json.dumps(tree)))
var tree = {{ tree }};

Using Python Data in Jinja

If the data is not being passed to JavaScript but used in Jinja, you can omit JSON rendering and use Python data directly:

return render_template('tree.html', tree=tree)
{% for item in tree %}
<li>{{ item }}<li>
{% endfor %}

The above is the detailed content of Why Does My JavaScript Get a SyntaxError When Rendering JSON Data from a Jinja Template?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn