如何使用 Flask 和 HTML 从 python 列表创建下拉菜单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45877080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create dropdown menu from python list using Flask and HTML
提问by DeeChok
I'm trying to create a dropdown menu in HTML using info from a python script. I've gotten it to work thus far, however, the html dropdown displays all 4 values in the lists as 4 options.
我正在尝试使用 python 脚本中的信息在 HTML 中创建一个下拉菜单。到目前为止,我已经让它工作了,但是,html 下拉列表将列表中的所有 4 个值显示为 4 个选项。
Current: Option 1:Red, Blue, Black Orange; Option 2:Red, Blue, Black, Orange etc. (Screenshot in link) Current
当前:选项 1:红色、蓝色、黑橙色;选项 2:红色、蓝色、黑色、橙色等(链接中的截图) 当前
Desired: Option 1:Red Option 2:Blue etc.
期望:选项 1:红色 选项 2:蓝色等。
How do I make it so that the python list is separated?
如何使python列表分开?
dropdown.py
下拉菜单
from flask import Flask, render_template, request
app = Flask(__name__)
app.debug = True
@app.route('/', methods=['GET'])
def dropdown():
colours = ['Red', 'Blue', 'Black', 'Orange']
return render_template('test.html', colours=colours)
if __name__ == "__main__":
app.run()
test.html
测试.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dropdown</title>
</head>
<body>
<select name= colours method="GET" action="/">
{% for colour in colours %}
<option value= "{{colour}}" SELECTED>{{colours}}</option>"
{% endfor %}
</select>
</select>
</body>
</html>
采纳答案by Bear Brown
you have a typo, replace colours
to colour
你有一个错字,替换colours
为colour
<option value= "{{colour}}" SELECTED>{{colours}}</option>"
replace to
替换为
<option value= "{{colour}}" SELECTED>{{ colour }}</option>"
<!-- ^^^^ -->
回答by ettanany
You need to use {{colour}}
in both places (instead of {{colours}}
in the second place):
您需要{{colour}}
在两个地方使用(而不是{{colours}}
在第二个地方):
<select name="colour" method="GET" action="/">
{% for colour in colours %}
<option value="{{colour}}" SELECTED>{{colour}}</option>"
{% endfor %}
</select>
Note that using selected
inside the loop will add selected
attribute to all options and the last one will be selected, what you need to do is the following:
请注意,selected
在循环内使用将为selected
所有选项添加属性并选择最后一个,您需要做的是以下内容:
<select name="colour" method="GET" action="/">
<option value="{{colours[0]}}" selected>{{colours[0]}}</option>
{% for colour in colours[1:] %}
<option value="{{colour}}">{{colour}}</option>
{% endfor %}
</select>