次世代 Hugo

無駄を削ぎ、本質を研ぐ

建立首頁 Template

Sam Xiao's Avatar 2025-07-09

Hugo 預設以 home.html 提供首頁 Template,並搭配 _index.scss_index.js

Version

Hugo 0.147.8

Create Markdown

$ hugo new _index.md
  • hogo new : 根據 archetypes/default.md 樣板建立 markdown
  • _index.md : _index.md 是專門用來當首頁的 markdown

_index.md

content/_index.md

+++
title = "My Homepage"
date = 2023-01-01T08:00:00-07:00
draft = false
+++

Laborum voluptate pariatur ex culpa magna nostrud est incididunt fugiat
pariatur do dolor ipsum enim. Consequat tempor do dolor eu. Non id id anim anim
excepteur excepteur pariatur nostrud qui irure ullamco.
  • 在 Front Matter 建立 title page variable

Homepage Template

home.html

{{ define "main" }}
  {{ partial "header.html" . }}
  <main class="home">
    <h2>Welcome to {{ .Site.Title }}</h2>
    <h3>This is {{ .Title }}</h3>
    <p><a href="/posts">All Posts</a></p>
    <p><a href="/about">About</a></p>
  </main>
  {{ partial "footer.html" . }}
{{ end }}
  • layouts 目錄下建立 home.html 建立首頁 template

Line 1

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

Line 2

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

Line 3

<main class="home">
  <h2>Welcome to {{ .Site.Title }}</h2>
  <h3>This is {{ .Title }}</h3>
  <p><a href="/posts">All Posts</a></p>
  <p><a href="/about">About</a></p>
</main>
  • index.html 主要內容都放在 <main> 底下,且搭配 home 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

Home Style

assets/scss/_home.scss

.home {
  margin: 3rem auto;
  padding: 1rem;
  max-width: 600px;
  text-align: center;
}
  • 搭配 home.html 的 SCSS

Home Script

assets/js/_home.js

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

Conclusion

  • content 目錄的 _index.md 為首頁的 content(一定要加底線)
  • 無論在 layouts 下或 themes 下,都可使用 home.html 為首頁 template
  • home.html 相當精簡,只包含 header partial、footer partial 與 main block
  • assets/scsslayouts 下的目錄架構完全相同
  • assets/jslayouts 下的目錄架構完全相同
  • home.html 對應 _home.scss_home.js 方便維護,不必將所有 SCSS 與 JavaScript 都寫在 main.scssmain.js