Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables from Flask to JavaScript

I looked at similar forums but was not able to get any of the solutions to work. I am trying to pass variables from Flask to my JavaScript file. These values then will be used for PubNub from my JavaScript file.

Here is part of my Python code:

@app.route("/mysettings/") def user_settings():          return render_template('Settings.html',  project_name = session['project_name'] , publish_key = session['publish_key'] , subscribe_key = session['subscribe_key'] ) 

Here is part of my JavaScript code (app.js):

var settings = {         channel: {{project_name}},         publish_key: {{publish_key}},         subscribe_key: {{subscribe_key}}     }; 

this code works if I use it in my Settings.html file but not in the app.js file.

like image 419
pang Avatar asked May 16 '16 17:05

pang


People also ask

How do you pass a variable from Python to JavaScript in Flask?

To pass variables from Python Flask to JavaScript, we can call render_template with the data argument with the dictionary of data we want to pass to the template. to call render_template with the template file name and the data set to the data dict with the data we want to pass to the template.

Can Flask be used with JavaScript?

You will need HTML to make a Flask-based website. You don't strictly need CSS or JavaScript, but you'll very, very likely want to use the former and, depending what you need your site to do, you'll likely use the latter, too. You can accommodate CSS and JS files as 'static' files in your Flask build.

How do I pass a Python variable to HTML?

Solution. In email. html change {{userEmail}} to {userEmail} . Then you should be able to use Python string formatting to add the userEmail variable.


1 Answers

The mobiusklein answers is pretty good, but there is "hack" you should consider. Define your Javascript method to receive params and send data as params to your function.

main.py

@app.route('/') def hello():     data = {'username': 'Pang', 'site': 'stackoverflow.com'}     return render_template('settings.html', data=data) 

app.js

function myFunc(vars) {     return vars } 

settings.html

<html>     <head>          <script type="text/javascript" {{ url_for('static', filename='app.js')}}></script>          <script type="text/javascript">             myVar = myFunc({{data|tojson}})          </script>     </head> </html> 
like image 124
Mauro Baraldi Avatar answered Sep 18 '22 23:09

Mauro Baraldi