file.py
app = Flask(__name__)
with open ('test.txt', 'r') as f:
f_contents = f.read()
#print(f_contents)
@app.route("/")
def index():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
test.txttest.txt的主要内容将是大约50个单词的
1) This is a test file
2) With multiple lines of data...
3) Third line
index.html我想在HTML 中显示test.txt的内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>
</p>
</body>
</html>
在Flask中,您可以在render_template
函数中传递变量。我的建议是将文件的内容传递给您的模板,如下所示:
f = open("test.txt", "r")
file = f.read()
@app.route("/")
def index():
return render_template("index.html", text=file)
之后,您可以打印出该值。index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>
{% print(text) %}
</p>
</body>
</html>