次世代 Hugo

無駄を削ぎ、本質を研ぐ

建立特定頁面 Template

Sam Xiao's Avatar 2025-07-09

除了 Homepage 外,有些頁面也會特別客製化,如 About、Series …等,我們也可針對這類頁面設計特別 Template,並搭配獨立 SCSS 與 JavaScript。

Version

Hugo 0.147.8

Content

content/about.md

+++
title = "About me"
date = 2023-01-01T08:00:00-07:00
draft = false
type = "page"
layout = "about"
+++

This is the about page. You can write information about your site here.

content 目錄下建立 about.md,此為 about.html 的 Content 與 Front Matter,用來儲存資料:

  • type:指定 content type,這類特殊的頁面,content type 預設為 page
  • layout:指定 layout 名稱,通常會跟頁面名稱相同,方便管理

Page Template

layouts/page/about.html

{{ define "main" }}
  <main class="about">
    <h1>{{ .Title }}</h1>
    <article>{{ .Content }}</article>
  </main>
{{ end }}
  • 特殊頁面的 template 必須建立在 layoutspage 目錄下

Line 1

{{ define "main" }}
{{ end }}
  • 配合 baseof.html 定義 main block

Line 2

<main class="about">
  <h1>{{ .Title }}</h1>
  <article>{{ .Content }}</article>
</main>
  • about.html 主要內容都放在 <main> 底下,且搭配 about class

Baseof Template

layouts/baseof.html

<!doctype html>
<html lang="en">
  <head>
    {{ partial "css.html" . }}
  </head>
  <body>
    {{ block "main" . }}{{ end }}
    {{ partial "js.html" . }}
  </body>
</html>
  • 所有 template 基礎的 baseof.html

Line 10

<body>
  {{ block "main" . }}{{ end }}
</body>
  • <body> 內引用 main block

About Style

assets/scss/page/_about.scss

.about {
  margin: 2rem auto;
  padding: 1rem;
  line-height: 1.8;
  max-width: 720px;
}
  • 搭配 about.html 的 SCSS

About Script

assets/js/page/_about.js

export const initAbout = () => {
  console.log('initAbout()')
}
  • 搭配 about.html 的 JavaScript

Conclusion

  • 一般討論 Template 都會將注意力放在 home.htmlsingle.htmllist.html,但實務上還會遇到客製化的 Template
  • content/about.md 最後會變成 /about/index.html,而非 /about.html
  • 無論在 layouts 下或 themes 下,都可在 page 目錄建立特殊 Template
  • about.html 相當精簡,只包含 main block
  • assets/scsslayouts 下的目錄架構完全相同
  • assets/jslayouts 下的目錄架構完全相同
  • about.html 對應 _about.scss_about.js 方便維護,不必將所有 SCSS 與 JavaScript 都寫在 main.scssmain.js