TEMPLATES

Section templates

在區段模板中新增內容與 Front Matter

要有效利用區段模板,你需要首先了解 Hugo 的 內容組織方式,特別是 _index.md 在為區段和其他列表頁面新增內容與 Front Matter 中的作用。

區段模板查找順序

請參閱 模板查找順序

範例:創建一個預設的區段模板

layouts/_default/section.html
{{ define "main" }}
  <main>
    {{ .Content }}

    {{ $pages := where site.RegularPages "Type" "posts" }}
    {{ $paginator := .Paginate $pages }}

    {{ range $paginator.Pages }}
      <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
    {{ end }}

    {{ template "_internal/pagination.html" . }}
  </main>
{{ end }}

範例:使用 .Site.GetPage

接下來的 .Site.GetPage 範例假設以下的專案目錄結構:

.
└── content
    ├── blog
    │   ├── _index.md   <-- title: My Hugo Blog
    │   ├── post-1.md
    │   ├── post-2.md
    │   └── post-3.md
    └── events
        ├── event-1.md
        └── event-2.md

如果沒有找到 _index.md 頁面,.Site.GetPage 會返回 nil。因此,如果 content/blog/_index.md 不存在,模板將顯示區段名稱:

<h1>{{ with .Site.GetPage "/blog" }}{{ .Title }}{{ end }}</h1>

由於 blog 目錄有一個包含 Front Matter 的區段索引頁 content/blog/_index.md,上述代碼將返回以下結果:

<h1>My Hugo Blog</h1>

然而,如果我們在 events 區段中嘗試相同的代碼,由於 content/events/_index.md 不存在,Hugo 會默認顯示區段名稱:

<h1>{{ with .Site.GetPage "/events" }}{{ .Title }}{{ end }}</h1>

這會返回以下結果:

<h1>Events</h1>