點燈坊

新しいことを始めるのに、遅すぎる挑戰はない

為特定頁面設計 Layout

Sam Xiao's Avatar 2024-05-01

除了 Homepage 外,有些頁面也會特別客製化,如 About、Series …等,我們也可針對這類頁面設計特別 Layout。

Version

Hugo 0.125.2

Page

about01

  • 以上資料並非直接寫在 HTML,而是由 Markdown 與 Template 所合成

Content

content/about.md

---
title: My About
description: About Page with page layout
subtitle: My Repository
type: page
layout: about
---
  • content 目錄下建立 about.md,此為 about.html 的 content 與 front matter,用來儲存資料
  • type:指定 content type,這類特殊的頁面,content type 預設為 page
  • layout:指定 layout 名稱,通常會跟頁面名稱相同,方便管理

Layout

layouts/page/about.html

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    {{ $title := "Hugo Lab" }}
    <title>{{ $title }}</title>
    <link rel="stylesheet" href="/style.css" />
  </head>
  <body>
    <h1 class="title">{{ .Title }}</h1>
    <h2 class="description">{{ .Description }}</h2>
    <p class="subtitle">{{ .Params.Subtitle }}</p>
  </body>
</html>
  • 特殊頁面的 layout 必須建立在 layoutspage 目錄下

Line 8

<link rel="stylesheet" href="/style.css" />
  • style.css 的路徑需改成 /style.css,由於 page/about.html 實際上在 public 會變成 about/index.html,所以 style.css 會被誤認為about/style.css 而讀取不到

Style

static/style.css

.title {
  color: #f00;
  font-size: 2rem;
  font-weight: 700;
}

.description {
  font-size: 1.1rem;
}

.subtitle {
  font-size: 1rem;
  color: #00f;
}

Conclusion

  • 一般討論 layout 都會將注意力放在 homepage、single page 與 list page,但實務上還會遇到客製化的頁面與其 layout
  • content/about.md 最後會變成 /about/index.html,而非 /about.html

Reference

Hugo, Template look order