Home  >  Article  >  Backend Development  >  How to Pass Data from Flask to JavaScript in a Template and Use it with Google Maps?

How to Pass Data from Flask to JavaScript in a Template and Use it with Google Maps?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 13:57:27975browse

How to Pass Data from Flask to JavaScript in a Template and Use it with Google Maps?

Passing Data from Flask to JavaScript in a Template

Issue: You want to utilize a dictionary retrieved from an API call in your JavaScript code within a Flask template, particularly to pass long/lat tuples to the Google Maps API.

Solution:

To pass variables from Flask to JavaScript in a template, you can use the {{ variable }} syntax anywhere within it. For instance, in your get_data.html template:

<html>
<head>
  <script>
    var someJavaScriptVar = '{{ geocode[1] }}';
  </script>
</head>
<body>
  <p>Hello World</p>
  <button onclick="alert('Geocode: {{ geocode[0] }} ' + someJavaScriptVar)">Click me</button>
</body>
</html>

This generates the HTML output that contains the JavaScript variable assignment.

To pass a list to JavaScript, you'll need to create an array definition in your output:

<html>
  <head>
    <script>
      var myGeocode = ['{{ geocode[0] }}', '{{ geocode[1] }}'];
    </script>
  </head>
  <body>
    <p>Hello World</p>
    <button onclick="alert('Geocode: ' + myGeocode[0] + ' ' + myGeocode[1])">Click me</button>
  </body>
</html>

Jinja2 also supports advanced Python constructs. For example, the above can be shortened to:

<html>
<head>
  <script>
    var myGeocode = [{{ ', '.join(geocode) }}];
  </script>
</head>
<body>
  <p>Hello World</p>
  <button onclick=&quot;alert('Geocode: ' + myGeocode[0] + ' ' + myGeocode[1])&quot; />
</body>
</html>

You can also leverage Jinja2 filters. If your dictionary is in JSON format, you can use the tojson filter to convert it to a JavaScript object:

<script>
  var myGeocode = {{ geocode|tojson }};
</script>

The above is the detailed content of How to Pass Data from Flask to JavaScript in a Template and Use it with Google Maps?. 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