我们之前的视图函数,返回的都是简单的'Hello Wolrd'之类的字符串,怎么返回一个html呢?首先我们在templates文件夹建立一个html文件,内容随便写一点如下:
IndexThis is index page
我们可以使用Flask对象app的send_static_file方法,使视图函数返回一个静态的html文件,但现在我们不使用这种方法,而是使用flask的render_template函数,它功能更强大。
从flask中导入render_template,整体代码如下:
from flask import Flask, render_template
import config
app = Flask(__name__)
app.config.from_object(config)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run()
render_template函数会自动在templates文件夹中找到对应的html,因此我们不用写完整的html文件路径。用浏览器访问'/'这个地址,显示结果如下:
那么为何称之为模板呢?因为render_template不仅能渲染静态的html文件,也能传递参数给html,使一个html模板根据参数的不