如何在 jinja flask 中为输入创建 for 和 if 循环

How to create for and if loop for inputs in jinja flask

我有一个 python 片段来附加一个列表,并将其作为字符串返回。输入框会一个一个弹出,直到end for。这个片段工作得很好。

x=4
list=[]
for i in range(1,x):
    for j in range(1,x):
         if i<j:
             a = input(' {} vs {} ?: '.format(i,j))
             list.append(a)
             string = " ".join(str(x) for x in list)

print(string)

输出:

1 vs 2 ?: 1
1 vs 3 ?: 1
2 vs 3 ?: 1
1 1 1

但是我想在 flask 中使用它,我如何才能以正确的语法在 jinja 中应用它?到目前为止,这是我尝试过的方法,但没有成功:

def function(): 
    if request.method == 'POST':
        x = 4
        list = []
        a = request.form["a"]
        list.append(a)
        string = " ".join(str(x) for x in list)

        return render_template('index.html', x=x, a=a, string=string)

    return render_template('index.html')

和模板:

<form method="post" action="{{ url_for('function') }}">
          <div>
            {% for i in range(1, x) %}
              {% for j in range(1, x) %}
                {% if i < j %}
                <p>' {} vs {} ?: '.format(i,j)</p>
                <input type="text" name="a" id="a">
                  <div class="input-group-append">
                    <button class="btn type="submit" value="Submit">Enter</button>
                  </div>
                  {% endif %} 
              {% endfor %} 
            {% endfor %}   
        </div>
</form>

{{string}}

您可以使用getlist函数查询所有输入字段的同名属性值

@app.route('/', methods=['GET', 'POST'])
def index():
    x = 4
    if request.method == 'POST':
        data = request.form.getlist('a', type=str)
        rslt = ' '.join(data)
    return render_template('index.html', **locals())
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form method="post">
    {% set ns = namespace(idx=0) %}
    {% for i in range(1,x) %}
      {% for j in range(i+1,x) %}
      <div>
        <label>{{ '{} vs {}'.format(i,j) }}</label>
        <input type="text" name="a" value="{{data and data[ns.idx]}}" />
      </div>
      {% set ns.idx = ns.idx + 1 %}
      {% endfor %}
    {% endfor %}
      <input type="submit" />
    </form>
    {% if rslt %}
    <output>{{ rslt }}</output>
    {% endif %}
  </body>
</html>

你也可以写短一点

from itertools import combinations

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        data = request.form.getlist('a', type=str)
        rslt = ' '.join(data)
    x = 4
    pairs = combinations(range(1,x), 2)
    return render_template('index.html', **locals())
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form method="post">
      {% for i,j in pairs %}
      <div>
        <label>{{ '{} vs {}'.format(i,j) }}</label>
        <input type="text" name="a" value="{{data and data[loop.index0]}}" />
      </div>
      {% endfor %}
      <input type="submit" />
    </form>
    {% if rslt %}
    <output>{{ rslt }}</output>
    {% endif %}
  </body>
</html>