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 java script 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.
The reason is that
jinja2
needs to be used to perform the substitution, which from your code doesn't appear to be happening.Chances are you're serving
app.js
as a static file, which means that it is never looked at by the templating engine machinery, just served as is.You can accomplish what you're describing by serving
app.js
from a URL which is tied to an action which passes the contents ofapp.js
through Flask'srender_template
function, performingjinja2
substitutions, and all the other customization information, but that meansjinja2
has to parse the whole file, which can be expensive.You might try to pass those variables along using an AJAX request responded to by an action that sends back that same data in JSON. This is a much more common practice, and has the added value of making that data visible to other resources.
Simple way to pass variables from flask view to template to javascript file with simple example mentioned by @mauro.
main.py
settings.html
app.js
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.js
settings.html