模板渲染其實就是靜態檔案的展示
app.py
import os
from flask import Flask, render_template, jsonify
app = Flask(__name__)
@app.route('/')
def home():
return 'flask home2'
@app.route('/index/')
def index():
# #返回字串
# return '<b>flask home2</b>'
# #模板渲染
return render_template('index.html', name='小新')
# # #返回json
# # jsonify: 將字典轉換為json格式
# return jsonify({'name': '小新', 'age': 18})
if __name__ == '__main__':
# print(f"Starting server on port {os.environ.get('FLASK_RUN_PORT', 'not set')}")
# app.run(debug=True, port=5001, host='0.0.0.0')
port = 8884
print(f"Starting Flask server on port {port}")
app.run(debug=True, port=port, host='0.0.0.0')
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模板渲染</title>
{#匯入css檔案、這裡css檔名最好和html檔名一致#}
{#3種匯入靜態檔案的方式#}
{# <link rel="stylesheet" href="../static/index.css">#}
{# <link rel="stylesheet" href="/static/index.css">#}
<link rel="stylesheet", href="{{ url_for('static', filename='index.css') }}">
</head>
<body>
<h1>模板渲染</h1>
<hr>
{#name 變數是從app.py中return 傳過來的變數名#}
<h2>{{ name }}</h2>
</body>
</html>
index.css
/*這裡h2是指在html中的h2標籤,html中使用h2標籤中的內容會變成紅色*/
h2 {
color: red;
}