How Can I Pass Data from Flask to JavaScript in Templates?

Patricia Arquette
Release: 2024-10-28 13:01:30
Original
899 people have browsed it

How Can I Pass Data from Flask to JavaScript in Templates?

Passing Data from Flask to JavaScript in Templates

In Flask, you can pass data from your Python code to JavaScript code within your templates. This is useful for populating interactive elements like maps or charts.

Standard Approach

A basic method involves using {{ variable }} in your template, which can contain any value from your Python code. For example:

# Python code
geocode = (latitude, longitude)
return render_template('get_data.html', geocode=geocode)
Copy after login
# HTML template
<head>
  <script>
    var someJavaScriptVar = '{{ geocode[1] }}';
  </script>
</head>
Copy after login

Using the tojson Filter

Jinja2 also provides a tojson filter. This can be used to convert a Python object into a JSON string, which can be directly passed to JavaScript:

# Python code
geocode = (latitude, longitude)
return render_template('get_data.html', geocode=geocode|tojson)
Copy after login
# HTML template
<head>
  <script>
    var myGeocodeObj = {{ geocode|tojson }};
  </script>
</head>
Copy after login

Advanced Usage

Jinja2 supports various other features for constructing JavaScript code, including loops and conditional statements. For more information, refer to the Jinja2 documentation.

The above is the detailed content of How Can I Pass Data from Flask to JavaScript in Templates?. 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