Flask使用Jinja 2模板引擎来分离数据逻辑和展示层。
我们将模板文件按如下路径放置:
Apps folder/app.pytemplates|-/index.html
使用模板时,视图函数应当返回render_template()的调用结果。
例如下面的代码片段渲染模板index.html,并将渲染结果作为视图函数的返回值
from flask import Flask, render_templateapp = Flask(__name__)@app.route('/hello/')@app.route('/hello/<name>')def hello():return render_template('index.html', name=name)if __name__ == '__main__':app.run(debug = True)
在上面的代码中,模板文件index.html依赖于变量name,其内容如下:
<html><body>{% if name %}<h2>Hello {{ name }}.</h2>{% else %}<h2>Hello.</h2>{% endif %}</body></html>
模板文件的语法扩充了HTML,因此可以使用变量和逻辑。
在浏览器中访问http://127.0.0.1:8080/hello/alex:

