如何为jinja烧瓶中的输入创建for和if循环



我有一个python片段来附加一个列表,并将其作为字符串返回。输入框将一个接一个地弹出,直到结束。这个片段很好用。

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>

最新更新