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

How to Pass Data from Flask to JavaScript in Templates?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 02:29:29662browse

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>

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>

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>

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>

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!

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