如何循环Flask Jinja2表单输入..?

时间:2018-08-25 15:34:39

标签: python flask jinja2

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

enter image description here
这是我的 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)

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

那么..该怎么做..?

1 个答案:

答案 0 :(得分:2)

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

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>

您确定要为姓名和年龄设置相同的值吗?