I am passing variable from Flask to JavaScript using the method render_template.
I followed this post: Passing variables from flask to javascript , but it is not working for me
Here is my code:
@app.route('/')
def index():
return render_template('index.html')
@app.route('/debug')
def index_debug():
return render_template('index.html', debug=True)
I would like to read it from a JavaScript file. I tried using this method:
this is my html file:
<head>
<script type="text/javascript">
var debugMode = {{ debug }};
</script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js" crossorigin="anonymous"></script>
<script src="/static/index.js"></script>
</head>
But when i try accessing this variable in my index.js. the variable debugMode is undefined.
Try this
<head>
<script type="text/javascript">
window.debugMode = {{ debug }};
</script>
<script src="/static/index.js"></script>
</head>
If you want to read a variable from HTML in JS you ought to declare this var in window scope and read in JS file like this.
const myNewVar = window.debugMode
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.