admin管理员组

文章数量:1323035

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?

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?

Share Improve this question asked Nov 27, 2013 at 6:33 quantumtremorquantumtremor 3,9372 gold badges19 silver badges20 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Exposing a function and making an ajax call to it isn't a bad way to go. That approach es with the benefit of leaving a clear trail of function calls for maintainers.

http://api.jquery./jQuery.ajax/

http://flask.pocoo/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./ajax/ajax_in_action.htm

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')

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.

本文标签: