0

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.

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the response. But on my JS file, I am trying to read it : let debugMode= window.debugMode But window.debugMode is undefined
When you console.log window.debugMode in Chrome console, it's also undefined?
Yes. I tired to print it also in the console
Did you also check the page source? To be sure that window.debug has any value.
Yes. This is the header file in the HTML: <head> <script type="text/javascript"> window.debugMode = True; </script> <script src="/static/index.js"></script> <link rel="stylesheet" href="/static/index.css"> <script type="text/javascript" src="code.jquery.com/jquery-3.4.1.js" crossorigin="anonymous"></script> <script src="/static/index.js"></script> </head> (I can't put code or image in the comment)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.