Categories
Python Answers

How to pass variables from Python Flask to JavaScript?

Spread the love

Sometimes, we want to pass variables from Python Flask to JavaScript.

In this article, we’ll look at how to pass variables from Python Flask to JavaScript.

How to pass variables from Python Flask to JavaScript?

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.

For instance, in our view, we write

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

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.

Then in the settings.html template, we write

<html>
    <head>
         <script type="text/javascript" {{ url_for('static', filename='app.js')}}></script>
         <script type="text/javascript">
            myVar = myFunc({{ data | tojson }})
         </script>
    </head>
</html>

to add a script tag that interpolates the data variable from the render_template argument.

We use the tojson filter to convert it to a JavaScript object.

Conclusion

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.

2 replies on “How to pass variables from Python Flask to JavaScript?”

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.