python3-flask-5引用html頁面模版render_template


通過returnjsonify返回數據。使用者用瀏覽器等用具打開時,只能查看到源數據。
使用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_templatetemplates目錄讀取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 }}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM