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

My application calls an API call that returns a dictionary. I want to pass information from this dict to JavaScript in a view. I use the Google Maps API in JS in particular, so I would like to pass it a list of tuples with long / lat information. I know that render_template will pass these variables to the mind so they can be used in HTML, but how can I pass them JavaScript in the template?

 from flask import Flask from flask import render_template app = Flask(__name__) import foo_api api = foo_api.API('API KEY') @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) 
+69
javascript python flask jinja2
Jun 24 '12 at 14:50
source share
6 answers

You can use {{ variable }} anywhere in your template, not just the HTML part. Therefore, this should work:

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

Think of it as a two-step process: first, Jinja (uses the template flash memory) generates your text output. This is sent to the user who runs the JavaScript that he sees. If you want your Flask variable to be available in JavaScript as an array, you need to create an array definition in your output:

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

Jinja also offers more advanced constructs from Python, so you can shorten it to:

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

You can also use for loop, if and many others, see the Jinja2 documentation for more information.

Also look at the ford answer, which points to a tojson filter, which is in addition to the Jinja2 Standard Filter Set .

+90
Jun 24 2018-12-12T00:
source share

The ideal way to get almost any Python object into a JavaScript object is to use JSON. JSON is great for transferring data between systems, but sometimes we forget that it means JavaScript Object Notation. This means that injecting JSON into the template is the same as injecting JavaScript code that describes the object.

Flask provides a Jinja filter for this: tojson dumps the structure into a JSON string and makes it safe so that Jinja does not autostart it.

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

This works for any Python structure that is serializable JSON:

 python_data = { 'some_list': [4, 5, 6], 'nested_dict': {'foo': 7, 'bar': 'a string'} } 
 var data = {{ python_data|tojson }}; alert('Data: ' + data.some_list[1] + ' ' + data.nested_dict.foo + ' ' + data.nested_dict.bar); 
+61
Apr 14
source share

When using an attribute in an HTML element, avoid using inline scripts, which in turn means that you can use stricter CSP rules to increase security.

Specify a data attribute, for example:

 <div id="mydiv" data-geocode="{{ geocode|tojson }}">...</div> 

Then access it in a static JavaScript file like this:

 // Raw JavaScript var geocode = JSON.parse(document.getElementById("mydiv").dataset.geocode); // jQuery var geocode = JSON.parse($("#mydiv").data("geocode")); 
+4
Jun 30 '17 at 7:17
source share

Another alternative solution for those who want to pass variables to a script that is obtained using a flash, I managed to get this working by specifying the variables outside, and then calling the script as follows:

  <script> var myfileuri = "/static/my_csv.csv" var mytableid = 'mytable'; </script> <script type="text/javascript" src="/static/test123.js"></script> 

If I enter jinja variables in test123.js , this will not work and you will get an error message.

+2
Feb 10 '17 at 11:34 on
source share

Alternatively, you can add an endpoint to return your variable:

 @app.route("/api/geocode") def geo_code(): return jsonify(geocode) 

Then do XHR to get it:

 fetch('/api/geocode') .then((res)=>{ console.log(res) }) 
+2
May 15 '17 at 18:21
source share

Some js files come from the Internet or library, they are not written by yourself. The code they receive changes as follows:

 var queryString = document.location.search.substring(1); var params = PDFViewerApplication.parseQueryString(queryString); var file = 'file' in params ? params.file : DEFAULT_URL; 

This method makes js files immutable (keep independence) and pass variables correctly!

0
Nov 22 '17 at 4:28
source share



All Articles