python - 在响应式下拉菜单中设置“选定”标签并使用 Flask 和 jinja2 进行选择

我有一个 flask 服务器,它将选项字典发送到下拉列表或选择(以形式)。

这是 Python 代码:

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

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

这是神社代码:

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

现在,我想将 selected 属性设置为选项之一,例如 Python 代码中的 option2,如 return flask.render_template("index.html", options=options, selected='option2')selected='o2'

有人可以帮我实现吗这个?

回答1

将所需选项传递给视图后,通过

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

您只需创建一个条件来断言 selected 变量是否与循环中的当前 id 相同,以便将 selected 属性添加到 option 或不:

<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>

相似文章

随机推荐

最新文章