在Flask中,如何将python列表打印到Jinja模板?

时间:2017-09-08 00:15:49

标签: python-3.x list loops flask jinja2

我有一些用于计算笛卡尔积的列表:

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代码时,我得到了返回的列表。

我可能在哪里遇到问题?

2 个答案:

答案 0 :(得分:1)

cpl返回一个元组列表,它不是单个值。也许那令人困惑的金贾。您可以创建嵌套for循环,也可以在渲染模板之前尝试将这些元组转换为字符串。

例如,尝试添加

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

答案 1 :(得分: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 %}