Categories
Python Answers

How to pass data from Flask to JavaScript in a template?

Spread the love

Sometimes, we want to pass data from Flask to JavaScript in a template.

In this article, we’ll look at how to pass data from Flask to JavaScript in a template.

How to pass data from Flask to JavaScript in a template?

To pass data from Flask to JavaScript in a template, we can interpolate variables in the template.

For instance, we write

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

to add the template with the geocode array values interpolated into the template.

We can use the tojson filter to convert JSON strings into JavaScript objects.

For instance, we write

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

to use the tojson filter to parse the geocode variable into a JavaScript object.

Conclusion

To pass data from Flask to JavaScript in a template, we can interpolate variables in the template.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *