Passing Data from Flask to JavaScript in a Template
In Flask applications, a common requirement is to pass data from Python to JavaScript within a template. This data can originate from database queries, API responses, or any other source.
One way to achieve this is through Jinja2, the template engine used by Flask. Jinja2 provides a way to embed Python expressions within HTML templates. By enclosing expressions in double curly braces ({{ ) and ( }}), it's possible to access variables, perform operations, and even execute control structures.
To pass a Python variable to JavaScript, you can simply include it within a script tag in your template. For example, suppose you have a list of tuples representing geographical coordinates stored in the geocode variable. You can pass them to JavaScript as follows:
<code class="html"><script> var myGeocode = [{{ ', '.join(geocode) }}]; </script></code>
Jinja2 offers additional features that enhance the integration between Python and JavaScript. One useful filter is tojson(), which converts a Python object into JSON format. This filter can be particularly handy for passing complex data structures to JavaScript.
Here's an example using tojson():
<script> var myGeocode = {{ geocode | tojson }}; </script>
Once the data is passed to JavaScript, you can access and manipulate it using JavaScript's native data types and methods.
The above is the detailed content of How Can I Pass Data from Flask to JavaScript in a Template?. For more information, please follow other related articles on the PHP Chinese website!