Skip to content
Advertisement

How do I set the variables in this javascript file to match variables from Flask/Python?

I have a Javascript file that enables drop down menus dynamic (i.e. a selection from one drop down impacts the others). I would like to use this file in conjunction with multiple forms but I have hard-coded the starting variables in this file to html elements ‘inverter_oem’ and ‘inverter_model_name’.

In other forms, I will need to reference different objects.

How can I accomplish this? I would like to create the variables in Javascript this way:

JavaScript

My current approach is to try and pass variables from the Flask route using render_template. (I have also tried other stack overflow solutions but no luck)

JavaScript

The jinja template form is as follows

JavaScript

However, I dont get a value in the javascript file when I try

JavaScript

Here is the original JScode with the “hardcoded” variables

JavaScript

Advertisement

Answer

Jinja does not know that you want to pass a variable inside a JavaScript environment, so it cannot add the quotation marks automatically around a string variable. It just replaces {{ var }} with value1 causing a syntax error. Just add the quotation marks and then you can access myVar inside the JS environment:

JavaScript

Note: if you want to pass a more complex data structure and/or user submitted values, you should look at the tojson filter that safely renders the data.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement