Home > Software design >  How to create for and if loop for inputs in jinja flask
How to create for and if loop for inputs in jinja flask

Time:11-19

I have a python snippet to append a list, and returning it back as a string. The input box will pop up one by one until end for. This snippet works just fine.

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)

Output:

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

However I want to use it in flask, how can I apply this in jinja with correct syntax? here's what i've tried so far and it didn't work:

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')

and the template:

<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}}

CodePudding user response:

You can use the getlist function to query all the values of the input fields with the same name attributes.

@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>

You can also write it a little shorter.

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>
  • Related