41

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.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
pang
  • 443
  • 1
  • 4
  • 6

5 Answers5

50

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>
Community
  • 1
  • 1
Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
37

Simple way to pass variables from flask view to template to javascript file with simple example mentioned by @mauro.

main.py

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

settings.html

<html>
    <head>
         <script type="text/javascript">
            var username = {{ data.username }}
            var site = {{ data.site }}
        </script>
        <script type="text/javascript" src="app.js"></script>
    </head>
</html>

app.js

function myFunc() {
    return username + site
}
shrishinde
  • 3,219
  • 1
  • 20
  • 31
  • 7
    This answer worked for me only after I changed `data.username ` to `data.username|tojson` (I'm passing variable whose name contains slashes, e.g. "/example/name" if that matters.) – Sam Oct 25 '17 at 19:54
  • Follow @joash answer below for the variables should be assigned the flask variable – R.S.K Aug 02 '21 at 10:58
11
<script type="text/javascript">
   var username ='{{ data.username }}'
   var site ='{{ data.site}}'
<script>
joash
  • 2,205
  • 2
  • 26
  • 31
  • 2
    This works well, but on vscode javascript checker will get angry about jinja's curly brackets. To suppress the warnings I added this to my settings.json:`"html.validate.scripts": false,` This suppresses javascript syntax checking on html files. – yomajo Jul 25 '22 at 16:45
6

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 of app.js through Flask's render_template function, performing jinja2 substitutions, and all the other customization information, but that means jinja2 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.

mobiusklein
  • 1,403
  • 9
  • 12
0

In this instance, you don't actually need to send your data with render_template() because your data is already stored in your session. Your session data is already available to a jinja2 template. (You might not be able to import it from app.js. You might need to include all the code explicitly in 'Settings.html'.)

main.py

@app.route("/mysettings/")
def user_settings(): 
    return render_template('Settings.html')

settings.html

<script type="text/javascript">
var settings = {
    channel: {{ session.project_name }},
    publish_key: {{ session.publish_key }},
    subscribe_key: {{ session.subscribe_key }}
};
</script>