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.
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>
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>
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!