使用 Flask/模板建立網站
外觀
當我們建立 Flask 應用程式時,我們經常希望返回一個 HTML 檔案,而不僅僅是一串 HTML 字串。使用模板,我們可以做到這一點,以及更多高階的事情,例如變數、迴圈、基礎模板等等。
要建立一個模板檔案,我們在一個名為 templates 的資料夾中建立一個 HTML 檔案。例如,讓我們建立一個名為 index.html 的 HTML 檔案,並在其中放入以下內容
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Welcome to my Website!</h1>
<p>Hello world!</p>
</body>
</html>
要顯示一個模板,我們使用 render_template() 函式。要使用它,我們首先需要從 Flask 模組匯入它
from flask import render_template
然後,我們在返回函式時使用 render_template() 函式。我們將模板 HTML 檔案的名稱傳遞到 render_template() 函式中。所以,類似於以下內容
@app.route("/template")
def template_page():
return render_template("index.html")
另一種提供 HTML 程式碼的方式是內聯提供。這是一個示例
from flask import *
app = Flask(__name__)
@app.route('/')
def inline_example();
return """
<!DOCTYPE html><html>
<head>
<title>My Inline Code Example</title>
</head>
<body>
<h1>You did it</h1>
Good Job!
</body>
</html>
"""
if __name__ == "__main__":
app.run(debug=true)
在這個示例中,HTML 不是從外部檔案載入的,而是直接提供給使用者。
在你的 Python 編輯器中,執行程式。然後開啟一個瀏覽器。導航到 http://127.0.0.1:5000/ ,你應該會看到一個網頁祝賀你。如果沒有,請檢查控制檯以進行除錯。