Home > Backend Development > Python Tutorial > 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
Release: 2024-10-30 13:57:27
Original
1090 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template