Home > Web Front-end > JS Tutorial > How to Pass Data from Flask to JavaScript in Templates?

How to Pass Data from Flask to JavaScript in Templates?

Susan Sarandon
Release: 2024-10-31 02:29:29
Original
676 people have browsed it

How to Pass Data from Flask to JavaScript in Templates?

Passing Data from Flask to JavaScript in Templates

When working with Flask, it's often necessary to pass data from the backend to the frontend for manipulation by JavaScript. This can be achieved through rendering templates.

Passing Data to JavaScript

The Jinja2 template engine used by Flask allows us to access Python variables directly within templates. To pass a variable from Python to JavaScript, simply enclose it with double curly braces {{ }}:

<code class="html"><head>
  <script>
    var myVariable = '{{ my_python_variable }}';
  </script>
</head></code>
Copy after login

Example: Passing Geospatial Data

Consider the following scenario where we want to pass a dictionary of geocoordinates to the Google Maps API in a template:

<code class="python"># Assuming 'events' is a dictionary
geocode = event['latitude'], event['longitude']
return render_template('my_template.html', geocode=geocode)</code>
Copy after login

To make this data available in JavaScript, we can use Jinja2:

<code class="html"><head>
  <script>
    var lat = '{{ geocode[0] }}';
    var lng = '{{ geocode[1] }}';
  </script>
</head></code>
Copy after login

Alternative: Using the tojson Filter

Jinja2 offers a tojson filter that converts a Python object into a JSON string, which can be directly embedded into a JavaScript variable:

<code class="html"><script>
  var geocode = {{ geocode|tojson }};
</script></code>
Copy after login

The above is the detailed content of How to Pass Data from Flask to JavaScript in Templates?. 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