Categories
Python Answers

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

Spread the love

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

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

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

To pass data from Python Flask to JavaScript in a template, we can use the tojson filter.

For instance, we write

<html>
  <head>
    <script>
      var myGeocode = {{ geocode|tojson }};
    </script>
  </head>
  <body>
    <p>Hello World</p>
    <button onclick="console.log(myGeocode[0], myGeocode[1])" />
  </body>
</html>

to convert the geocode dictionary to JSON and assign it to myGeocode .

And then we use myGeocode as an object within our JavaScript code.

Conclusion

To pass data from Python Flask to JavaScript in a template, we can use the tojson filter.

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 *