opensource25
opensource25

Reputation: 33

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?

Upvotes: 2

Views: 438

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39099

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>

Upvotes: 1

Related Questions