次世代 Hugo

無駄を削ぎ、本質を研ぐ

建立單筆文章 Template

Sam Xiao's Avatar 2025-07-09

Hugo 預設以 single.html 提供單筆文章 Template,並搭配 _single.scss_single.js

Version

Hugo 0.147.8

Single Template

layouts/single.html

{{ define "main" }}
  {{ partial "header.html" . }}
  <main class="single">
    <h1>{{ .Title }}</h1>
    <article>
      {{ .Content }}
    </article>
  </main>
  {{ partial "footer.html" . }}
{{ end }}
  • 為單筆 markdown 建立 single.html

Line 1

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

Line2

{{ partial "header.html" . }}
  • 引用 header partial

Line 3

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

Line 9

{{ partial "footer.html" . }}
  • 引用 footer partial

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 6

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

Single Style

assets/scss/_single.scss

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

Single Script

assets/js/_single.js

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

Conclusion

  • 無論在 layouts 下或 themes 下,都可使用 single.html 為單筆文章 template
  • single.html 相當精簡,只包含 header partial、footer partial 與 main block
  • assets/scsslayouts 下的目錄架構完全相同
  • assets/jslayouts 下的目錄架構完全相同
  • single.html 對應 _single.scss_single.js 方便維護,不必將所有 SCSS 與 JavaScript 都寫在 main.scssmain.js