首页 > 解决方案 > 如何循环 Flask Jinja2 表单输入..?

问题描述

我有一个可用于订票的程序,如果用户预订三张票,它的值存储到变量预订中,我想根据该变量预订的值进行循环表单输入。
像这个表格,如果我预订三个股票,表格也显示三个输入表格。

在此处输入图像描述
这是我的app.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    booking = 3
    return render_template('index.html')

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)

索引.html

    <body>
    <form action="">
        {% for contact in booking %}
        Name: <br>
        <input type="text" value="{{ contact }}"><br>
        Age: <br>
        <input type="text" value="{{ contact }}">
        {% endfor %}
    </form>
   </body>

所以..怎么做..?

标签: pythonflaskjinja2

解决方案


我测试了以下,这应该工作。将您的返回渲染模板重写为:

return render_template('index.html', booking = booking)

并重写你的html如下:

<body>
  <form action="">
    {% for i in range(booking) %}
      Name: <br>
      <input type="text" value="{{ contact }}"><br>
      Age: <br>
      <input type="text" value="{{ contact }}">
    {% endfor%}
   </form>
</body>

你确定你想要相同的姓名和年龄值吗?


推荐阅读