Home > Article > Web Front-end > How to Pass Data from Flask to JavaScript in Templates?
When working with Flask, it's often necessary to pass data from the backend to the frontend for manipulation by JavaScript. This can be achieved through rendering templates.
The Jinja2 template engine used by Flask allows us to access Python variables directly within templates. To pass a variable from Python to JavaScript, simply enclose it with double curly braces {{ }}:
<code class="html"><head> <script> var myVariable = '{{ my_python_variable }}'; </script> </head></code>
Consider the following scenario where we want to pass a dictionary of geocoordinates to the Google Maps API in a template:
<code class="python"># Assuming 'events' is a dictionary geocode = event['latitude'], event['longitude'] return render_template('my_template.html', geocode=geocode)</code>
To make this data available in JavaScript, we can use Jinja2:
<code class="html"><head> <script> var lat = '{{ geocode[0] }}'; var lng = '{{ geocode[1] }}'; </script> </head></code>
Jinja2 offers a tojson filter that converts a Python object into a JSON string, which can be directly embedded into a JavaScript variable:
<code class="html"><script> var geocode = {{ geocode|tojson }}; </script></code>
The above is the detailed content of How to Pass Data from Flask to JavaScript in Templates?. For more information, please follow other related articles on the PHP Chinese website!