[英]How to send data from flask to html template
我有一個小應用程序,從用戶那里獲取輸入,並根據它將數據顯示在html上。 我必須從flask發送數據到html上顯示但無法找到方法。 我遇到沒有錯誤。
[更新]:Python腳本:
from flask import Flask, render_template, request
import random
app = Flask(__name__, template_folder='templates')
@app.route('/', methods=['GET','POST'])
def samplefunction():
if request.method == 'GET':
return render_template('new.html')
if request.mthod == 'POST':
greetIn = ['hey', 'hi', 'hey there', 'hi there', 'hello', 'hola', 'yoo']
byeIn = ['bye', 'see you later', 'catch you later', 'toodles']
nameOut = ['my name is Fatty!!', 'Fatty is my name', 'you can call me Fatty', 'I go by the name of Fatty']
greetOut = ['hey there!', 'hi!', 'hi there!', 'hey!']
byeOut = ['bye bye', 'bye. see you later']
human1 = request.form['human']
if human1 in greetIn:
bot = random.choice(greetOut)
return render_template('new.html', bot=bot)
else:
bot = 'Sorry..no idea!!!'
return render_template('new.html', bot=bot)
if __name__ == "__main__":
app.run(debug=True)
HTML代碼:
<html>
<head>
<title>BOT</title>
<script>
var bot = {{ bot }}
</script>
</head>
<body>
<h1>Hello, type something to begin!</h1>
<form method='post'>
Human: <input type='text' name='human'><br>
Bot: {{ bot }}<br>
<input type="submit" name="action">
</form>
</body>
</html>
任何幫助,將不勝感激。
謝謝!
問題
由於初始return語句,函數samplefunction()
總是呈現new.html
而不包含變量。
def samplefunction():
return render_template('new.html')
固定
你需要添加if request.method == 'GET':
if request.method == 'POST':
那么你的代碼就可以了。 並通過@Harrison建議更改變量名稱作為另一個答案: bot = random.choice(greetOut)
not bot = random.choice(greetout)
更新的代碼
def samplefunction():
if request.method == 'GET':
return render_template('new.html')
if request.method == 'POST':
greetIn = ['hey', 'hi', 'hey there', 'hi there', 'hello', 'hola', 'yoo']
byeIn = ['bye', 'see you later', 'catch you later', 'toodles']
nameOut = ['my name is Fatty!!', 'Fatty is my name', 'you can call me Fatty', 'I go by the name of Fatty']
greetOut = ['hey there!', 'hi!', 'hi there!', 'hey!']
byeOut = ['bye bye', 'bye. see you later']
human1 = request.form['human']
if human1 in greetIn:
bot = random.choice(greetOut)
return render_template('new.html', bot=bot)
else:
render_template('new.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080, debug=True)
greetOut = ['hey there!', 'hi!', 'hi there!', 'hey!']
< - 問候0 ut
bot = random.choice(greetout)
< - greet o ut
除此之外,你的模板看起來很好。 如果你糾正你的大寫,它應該工作。
另外,不是強制性的,但您可以將Flask導入壓縮成1行,如下所示: from flask import Flask, render_template, request
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.