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 .
mensi Jun 24 2018-12-12T00: 00Z
source share