Home > Backend Development > Python Tutorial > How to Avoid JavaScript SyntaxErrors When Using Jinja Templates and JSON Data?

How to Avoid JavaScript SyntaxErrors When Using Jinja Templates and JSON Data?

Barbara Streisand
Release: 2024-12-11 11:03:11
Original
157 people have browsed it

How to Avoid JavaScript SyntaxErrors When Using Jinja Templates and JSON Data?

JavaScript raises SyntaxError with data rendered in Jinja template

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.

Using the tojson Filter

To render Python objects as safe JSON, use the tojson filter:

return render_template('tree.html', tree=tree)
Copy after login
Copy after login

In the template, use:

var tree = {{ tree|tojson }};
Copy after login

This safely dumps the data to JSON and marks it as safe to prevent escaping.

Dealing with Pre-Dumped JSON

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))
Copy after login

In the template, use:

var tree = {{ tree|safe }};
Copy after login

Using Markup

Alternatively, you can wrap the string in Markup before rendering:

return render_template('tree.html', tree=Markup(json.dumps(tree)))
Copy after login

In the template, you can use the value as:

var tree = {{ tree }};
Copy after login

Avoiding JSON for Jinja Use

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)
Copy after login
Copy after login
{% for item in tree %}
    <li>{{ item }}</li>
{% endfor %}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template