python3-flask-5引用html页面模版render_template
通过
return或jsonify返回数据。使用者用浏览器等用具打开时,只能查看到源数据。
使用render_template调用html页面,并结合html参数,
示例
- 创建python程序
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import json
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
@app.route("/index.html")
def index():
flask_data = 'Hello Flask!'
return render_template('index.html', flask_data=flask_data)
if __name__ == '__main__':
app.run('0.0.0.0', 5000)
- 创建html文件
flask项目根目录下创建
templates目录(用来存放html文件)。render_template从templates目录读取html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<h1>{{ flask_data }}</h1>
</body>
</html>
render_template调用templates目录中的index.html。并将flask_data数据传递至html文件中的{{ flask_data }}进行展示
传递字典
当 flask_data = {'name':'xiaoming', 'age':8}
需浏览器中展示 name 对应的值 xiaoming 。
变量应写成{{ flask_data.name }}

浙公网安备 33010602011771号