Home  >  Article  >  Backend Development  >  How Can I Pass Data from Flask to JavaScript in Templates?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 13:01:30794browse

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)
# HTML template
<head>
  <script>
    var someJavaScriptVar = '{{ geocode[1] }}';
  </script>
</head>

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)
# HTML template
<head>
  <script>
    var myGeocodeObj = {{ geocode|tojson }};
  </script>
</head>

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!

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