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:

const selecting_dropdown_menu = document.getElementById(variable1_from_flask);
const filtered_dropdown_menu = document.getElementById(variable2_from_flask);

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)

@db_queries.route('/db_query_dynamic_form/<form_name>', methods=['GET', 'POST'])
def db_query_dynamic_form(form_name):
    # use methods to get form and endpoint for outside loop

    if request.method == 'POST':
        # inside loop when form complete
        return render_template('list.html', result=query_results["filtered_tables"], columns=query_results["column_names"])

    # added variable to pass to jinja template
    return render_template(form_endpoint["endpoint"], form=form_endpoint["form"], var="value1")

The jinja template form is as follows

% extends "base.html" %}
{% block title %}Inverter Dynamic  Search{% endblock %}
{% block heading %}Inverter Dynamic Search{% endblock %}
{% block content %}

  <form method="POST">
    {{ form.hidden_tag()}}
    {{ form.inverter_oem.label }}{{ form.inverter_oem }}<br>
    {{ form.inverter_model_name.label }}{{ form.inverter_model_name }}<br>
    {{form.submit()}}

    {{test}}
  </form>
    <script>
      myVar = {{ var }}
    </script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="{{ url_for('static', filename='search_inverter_dynamic.js') }}"></script>


{% endblock %}

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

console.log(myVar);

Here is the original JScode with the “hardcoded” variables

//acquire inverter_oem value from form
const inverter_oem_select = document.getElementById('inverter_oem');
const inverter_model_name_select = document.getElementById('inverter_model_name');

//add event listener to capture selected oem in dropdown
inverter_oem_select.addEventListener('click', (e) => {
    let oem = '../modelNameByOEM//' +  e.target.value;
    console.log(oem);
    getIt(oem);
});

//recover a JSON containing the list of models from a specific oem
async function getIt(input) {
    try {
        const res = await axios.get(input);
        console.log(res.data);
        optionHTML = '';
        for (let modelName of res.data.modelNameOem) {
            //console.log(res.modelName.name);
            optionHTML += '<option value="' + modelName.name + '">' + modelName.name + '</option>';
            //console.log(optionHTML);
        }
        inverter_model_name_select.innerHTML = optionHTML;

    } catch (err) {
        console.log('Could not reach endpoint modelNameByOEM')
        console.log(err);
    };
}

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:

<script>
myVar = "{{ var }}"
</script>

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