Reputation: 3937
I know that you can simply call a variable from Flask by including return render_template('index.html', variable=newvariable)
in the Python file and
<script>
var JSVAR = '{{ newvariable }}';
</script>
in the index.html file. But what if I want to pass that variable onto a purely Javascript file that's included within the index.html file? I'm thinking I need to create an HTML 'variable' of sorts using the id parameter then use jQuery to call it, but I can't figure out the syntax.
Any ideas?
Upvotes: 5
Views: 9500
Reputation: 1
You can access the variable using a data attribute on an html element. You can then use a querySelector to access the value in that data attribute.The data-chart attribute holds the variable from the flask app
const chart-data = document.querySelector("#chart-div").getAttribute("data-chart")
That should get hold of the variable from the flask app.
Upvotes: 0
Reputation: 304
Just came across this same issue, here is what I did
from jinja2.environment import Template
def render_js():
file_content = open(path_to_jsfile, 'r').read()
template = Template(file_content)
return template.render(arg1='value1', arg2='value2')
Upvotes: 0
Reputation: 1647
Exposing a function and making an ajax call to it isn't a bad way to go. That approach comes with the benefit of leaving a clear trail of function calls for maintainers.
http://api.jquery.com/jQuery.ajax/
http://flask.pocoo.org/docs/patterns/jquery/
The second link has a more detailed description, but the general idea is you have a Flask app set up to handle requests from the browser, and in that application you set up a method that can have requests sent to it that will take care of passing your variable back out to the js client.
In the js script you then make an ajax call to that method's url, and have a callback function that processes the response. This approach can do some really, really cool things.
If you're not familiar with ajax, it might be useful to Google some tutorials. This one is half way decent as an overview: http://www.tutorialspoint.com/ajax/ajax_in_action.htm
Upvotes: 3