Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  47] [ 1]  / answers: 1 / hits: 84637  / 8 Years ago, mon, may 16, 2016, 12:00:00

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.


More From » python

 Answers
9

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>

[#62148] Saturday, May 14, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zahrafrancisr

Total Points: 176
Total Questions: 105
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;