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.

Kenny Smith
  • 729
  • 3
  • 9
  • 23

1 Answers1

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
Maciej Trzciński
  • 181
  • 1
  • 2
  • 9