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
Barbara StreisandOriginal
2024-12-11 11:03:11242browse

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)

In the template, use:

var tree = {{ tree|tojson }};

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))

In the template, use:

var tree = {{ tree|safe }};

Using Markup

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 }};

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)
{% 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!

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