2017-09-08 40 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

相關問題