Populating dropdown dynamically from list with Jinja

天大地大妈咪最大 提交于 2021-02-10 12:23:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!