2016-04-14 53 views
0

我是一名學習Flask的新手,並試圖弄清楚如何在我的小應用中傳遞數據。 下面的代碼在有效的移動播放時返回錯誤「錯誤代碼:未處理的異常」,我真的不知道什麼是錯的? (其他兩個選項都正常工作)。Flask:無法在Jinja中顯示字典html模板

py代碼: theBoard = [{1:'',2:'',3:'',4:'',5:'',6:'' ,7: ' '8:'',9:」「}]

@app.route('/test', methods=["GET", "POST"]) 
def test(): 
    if request.method == 'POST': 
     x = request.form['move'] 
     move = int(x) 
     valid_moves = [1,2,3,4,5,6,7,8,9] 
     if move not in valid_moves: 
      return 'you did not specify a valid move, please try again!' 
     elif theBoard[move] != ' ': 
      return 'you can not play that space, it is taken' 
     else: 
      theBoard[move] = 'X' 
      return render_template("test2.html", theBoard=theBoard) 

    return render_template("test.html") 

HTML代碼:

<table> 
{% for key, value in theBoard.iteritems() %} 
<h1>Key: {{key}}</h1> 
<h2>Value: {{value}}</h2> 
{% endfor %} 
</table> 
+0

我的縮進出了問題。第一個代碼:theBoard = [{1:'',2:'',3:'',4:'',5:'',6:'',7:'',8:'',9: ']}是.py文件的一部分 –

+0

我在錯誤日誌中找到了以下內容:文件「/home/majaokholm/mysite/flask_app.py」,第19行,在測試中 elif theBoard [move]!='': IndexError:列表索引超出範圍 –

+0

它一直存在,我只是現在發現它 –

回答

0

theBoard是一個列表,而在試驗()以及HTML模板你把它當作字典。用下面的代碼替換第一行,看看它是否有效。

theBoard = {1:' ', 2:' ', 3:' ', 4: ' ', 5:' ', 6: ' ', 7:' ', 8:' ', 9:' '} 
+0

不幸的是它也不起作用。我在錯誤日誌中發現了以下內容:文件「/home/majaokholm/mysite/flask_app.py」,第19行,在測試elif theBoard [move]!=''中:IndexError:列表索引超出範圍 –

+0

as評論你的問題(抱歉不適當地放置評論),請嘗試將board改爲字典,然後報告你的發現。 –

+0

運行先前的代碼時可能會生成日誌項 –

相關問題