前言
使用 render_template() 方法可以渲染模板,只要提供模板名称和作为参数传递给模板的变量就行。
一、 render_template() 方法
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
if __name__ == '__main__':
app.run()
说明:Flask 会在 templates 文件夹内寻找模板。因此,如果应用是一个模块, 那么模板文件夹应该在模块旁边;如果是一个包,那么就应该在包里面。
1 : 一个模块:
/application.py
/templates
/hello.html
2 : 一个包:
/application
/__init__.py
/templates
/hello.html
二、templates渲染模板
<head>
<meta charset="UTF-8">
<title>Hello from Flask</title>
</head>
<body>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}
</body>
</html>
注意:.html文件一定是在templates文件夹下
三、运行结果
请求路径:http://127.0.0.1:5000/hello/盘盘
启动服务后,运行结果: