Home > Backend Development > Python Tutorial > How to Pass Data from Flask to JavaScript in a Template?

How to Pass Data from Flask to JavaScript in a Template?

DDD
Release: 2024-10-31 10:41:29
Original
708 people have browsed it

How to Pass Data from Flask to JavaScript in a Template?

Passing Data from Flask to JavaScript in a Template

In Flask, the render_template() function passes variables to views for use in HTML. However, how can you pass data to JavaScript within the same template?

Consider the following example, where a Flask app calls an API that returns a dictionary. The goal is to pass longitude and latitude information to JavaScript for use with the Google Maps API.

<code class="python">from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def get_data():
    events = api.call(get_event, arg0, arg1)
    geocode = event['latitude'], event['longitude']
    return render_template('get_data.html', geocode=geocode)</code>
Copy after login

Solution

Flask allows you to use the {{ variable }} placeholder syntax anywhere in the template, including in JavaScript code.

To pass the geocode data to JavaScript, simply include it within the {{ }} placeholder:

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

This will insert the value of geocode[1] (the longitude) into the JavaScript variable someJavaScriptVar.

To pass the data as an array, you can use the join() function:

<code class="html"><script>
  var myGeocode = [{{ ', '.join(geocode) }}];
</script></code>
Copy after login

This will generate the following JavaScript:

<code class="javascript">var myGeocode = ['value_of_geocode[0]', 'value_of_geocode[1]'];</code>
Copy after login

You can also use advanced constructs such as for loops and if statements within the {{ }} placeholder. See the Jinja2 documentation for more details.

Additionally, you can use the tojson filter to convert Python objects to JSON strings, which can be directly used in JavaScript:

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

This approach provides a convenient way to pass complex data structures from Flask to JavaScript in your templates.

The above is the detailed content of How to Pass Data from Flask to JavaScript in a Template?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template