How To Access External Javascript Files Through Jinja[flask]?
Solution 1:
You need to understand how Jinja works. When you run the commmand
return render_template('main.html', var1 = 1, var2 = 2)
, it gets processed in the following way:
- The Flask server opens the main.html template
- Renders/replaces all the defined Jinja variables i.e. the context into the template
- Sends the rendered HTML to the client.
Hence the variables are not loaded into the {{ var }}
place-holders on the client side but at the server side.
Therefore to achieve what you are trying to do you could do something as follows: In main.html code:
<html><body><p>The first value is {{var1}}</p><script>var var2 = {{var2}};
<scriptsrc="main.js"></script></body></html>
In main.js code:
window.onload=function(){
console.log(var2);
};
Note: We have added the script inside HTML code before calling main.js which the dependent script.
Let me know if this solves your issue and you have understood the explanation.
Solution 2:
TLDR; Pass your flask variable to a global JS variable from your HTML file.
I don't think that it's possible to access external JavaScript files directly from Flask. But you can use this hack, it works with many templating languages (Jinja, EJS...)
main.py:
@app.route('/')defdefault():
return render_template('main.html', var1 = 1, var2 = 2)
main.html
<html><body><p>The first value is {{var1}}</p><!-- Insert this <script/> tag before loading you main.js --><scripttype="text/javascript">window.myVar1 = "{{var1}}"</script><scriptsrc="main.js"></script></body></html>
main.js
window.onload=function(){
// Now you can access to myVar1 directlyconsole.log(myVar1);
};
Post a Comment for "How To Access External Javascript Files Through Jinja[flask]?"