2017-09-08 38 views
-1

我有,我用它来计算笛卡尔乘积几个列表:在Flask中,如何将python列表打印到Jinja模板?

python.py:

@app.route('/output', methods = ['GET','POST']) 
def output(): 
    a = ['one','two'] 
    b = ['three','four'] 
    c = ['five'] 
    d = ['six','seven','eight'] 
    e = ['nine','ten','eleven'] 

    cpl = list(itertools.product(a,b,c,d,e)) 
    return render_template('output.html',cpl = cpl) 

output.html:

{% for cp in cpl %} 
    <p>{{ cp }} </p> 
{% endfor %} 

不过,我在返回黑屏。

当我在Jupyter中运行相同的python代码时,我得到了返回的列表。

我在哪里可能遇到问题?

+1

这可能只是与您当前的设置有关的问题。我在本地运行您的代码,并获得了预期的输出结果。 –

回答

1

cpl返回元组列表,它不是一个单一的值。也许这让Jinja感到困惑。你可以创建一个嵌套for循环,或者尝试在渲染模板之前将这些元组转换为字符串。

例如,尝试添加

strings = [str(c) for c in cpl] 
return render_template("output.html", cpl=strings) 
+0

疑问如此。该设置适用于我,生成元组字符串表示。 – alecxe

+0

我试过转换,它没有帮助。我会在哪里创建一个嵌套循环 - 在python或jinja? –

+0

如果设置对于@alecxe工作正常并且转换没有帮助,那么我会仔细检查其他所有内容。 – minterm

1

该工作方案如下:

python.py

@app.route('/output', methods = ['GET','POST']) 
def output(): 
    a = ['one','two'] 
    b = ['three','four'] 
    c = ['five'] 
    d = ['six','seven','eight'] 
    e = ['nine','ten','eleven'] 
    newArray = [] 
    newArray = [a, b, c, d, e] 
    cpl = list(itertools.product(*[i for i in newArray if i != []])) 
    return render_template('output.html',cpl = cpl) 

output.html:

{% for cp in cpl %} 
<p> {{ cp }} </p> 
{% endfor %} 
+0

很高兴你找到它。将此作为接受的答案。 – minterm

相关问题