'Set "selected" tag in responsive dropdown and select using Flask and jinja2

I have a flask server which sends a dictionary of options to a dropdown or selection (in form).

Here is the Python code:

@app.route("/", methods=['GET'])
def index_get():
    options = {'o1' : 'option1', 'o2' : 'option2', 'o3' : 'option3'}

    return flask.render_template("index.html", options=options)

This is the Jinja code:

<form method="post">
    <select name="test">
        {% for id,name in options.items() %}
            <option selected="" value="{{ id }}">{{name|safe}}</option>
        {% endfor %}
    </select>
</from>

Now, I want to set the selected attribute to one of the option, for example, option2 from the Python code like return flask.render_template("index.html", options=options, selected='option2') or selected='o2'.
Can someone help me implementing this?



Solution 1:[1]

Once you have passed your desired options to the view, via

return flask.render_template("index.html", options=options, selected='o2')

You just have to make a condition that would assert if the selected variable is the same as the current id in the loop, in order to add the selected attribute to the option or not:

<form method="post">
  <select name="test">
    {% for id,name in options.items() %}
      <option {% if selected == id %}selected{% endif %} value="{{ id }}">
        {{name|safe}}
      </option>
    {% endfor %}
  </select>
</from>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 β.εηοιτ.βε