问题
I have a Flask application which, from one of its routes, produces a list of data that I would then like to display in a dropdown menu on the front-end. The issue is, a different number of items will exist in each list that will populate the same dropdown menu. For example, one users accounts might have three items, while another's might have twenty.
My route looks like:
@app.route("/test", methods=['GET', 'POST'])
def test():
#list with 10 items is generated here
return render_template('test.html', title="test", list=list)
My HTML should look something like:
{% for x in list %}
<select>
<option value="tester">tester1</option>
<option value="tester2">tester2</option>
<option value="tester3">tester3</option>
<option value="tester4">tester4</option>
</select>
{% endfor %}
My list that I've passed to the template has ten items as indicated in the comment in my first code section (this is dynamic - could be any number next time), and my number of options for my drop down is static. What is the best programmatic solution for dynamically populating this dropdown (please do not include answers involving EXCEL or a database)?
回答1:
you can use the following syntax to loop your list
<select>
{% for x in list %}
<option value="{{x.id}}">{{x.text}}</option>
{% endfor %}
</select>
来源:https://stackoverflow.com/questions/59690257/populating-dropdown-dynamically-from-list-with-jinja