简体   繁体   中英

Flask: unable to display dictionary in Jinja html template

I am a newbee learning Flask and am trying to figure out how to pass data back and forth in my small app. The code below returns the error "Error code: Unhandled Exception" when a valid move is played and I really can't figure out what is wrong? (the other two options work fine.)

py code: 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 code:

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

theBoard is a list, while in test() as well as the html template you treat it as a dict. Replace first line with below code and see whether it works.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM