靜態檔案

驗證視圖和模板可以運作了,但它們現在看起來非常簡陋。可以加入一些 CSS 來為您建構的 HTML 佈局新增樣式。樣式不會改變,所以它是靜態檔案,而不是模板。

Flask 自動新增一個 static 視圖,它接受相對於 flaskr/static 目錄的路徑並提供它。 base.html 模板已經有一個連結到 style.css 檔案

{{ url_for('static', filename='style.css') }}

除了 CSS 之外,其他類型的靜態檔案可能是包含 JavaScript 函數的檔案,或是標誌圖片。它們都放置在 flaskr/static 目錄下,並使用 url_for('static', filename='...') 引用。

本教學課程不著重於如何編寫 CSS,因此您可以直接將以下內容複製到 flaskr/static/style.css 檔案中

flaskr/static/style.css
html { font-family: sans-serif; background: #eee; padding: 1rem; }
body { max-width: 960px; margin: 0 auto; background: white; }
h1 { font-family: serif; color: #377ba8; margin: 1rem 0; }
a { color: #377ba8; }
hr { border: none; border-top: 1px solid lightgray; }
nav { background: lightgray; display: flex; align-items: center; padding: 0 0.5rem; }
nav h1 { flex: auto; margin: 0; }
nav h1 a { text-decoration: none; padding: 0.25rem 0.5rem; }
nav ul  { display: flex; list-style: none; margin: 0; padding: 0; }
nav ul li a, nav ul li span, header .action { display: block; padding: 0.5rem; }
.content { padding: 0 1rem 1rem; }
.content > header { border-bottom: 1px solid lightgray; display: flex; align-items: flex-end; }
.content > header h1 { flex: auto; margin: 1rem 0 0.25rem 0; }
.flash { margin: 1em 0; padding: 1em; background: #cae6f6; border: 1px solid #377ba8; }
.post > header { display: flex; align-items: flex-end; font-size: 0.85em; }
.post > header > div:first-of-type { flex: auto; }
.post > header h1 { font-size: 1.5em; margin-bottom: 0; }
.post .about { color: slategray; font-style: italic; }
.post .body { white-space: pre-line; }
.content:last-child { margin-bottom: 0; }
.content form { margin: 1em 0; display: flex; flex-direction: column; }
.content label { font-weight: bold; margin-bottom: 0.5em; }
.content input, .content textarea { margin-bottom: 1em; }
.content textarea { min-height: 12em; resize: vertical; }
input.danger { color: #cc2f2e; }
input[type=submit] { align-self: start; min-width: 10em; }

您可以在 範例程式碼 中找到較不精簡版本的 style.css

前往 http://127.0.0.1:5000/auth/login,頁面應該看起來像下面的螢幕截圖。

screenshot of login page

您可以從 Mozilla 的文件 閱讀更多關於 CSS 的資訊。如果您更改了靜態檔案,請重新整理瀏覽器頁面。如果變更沒有顯示出來,請嘗試清除瀏覽器的快取。

繼續閱讀 部落格藍圖