Sections
概覽
分類是頂層的內容目錄,或者任何包含 _index.md 檔案的內容目錄。擁有 _index.md 檔案的內容目錄也被稱為 分支套件。分類模板會接收一個或多個頁面 集合 並將其放在 上下文 中。
一個典型的網站會包含一個或多個分類。例如:
content/
├── articles/ <-- 分類(頂層目錄)
│ ├── 2022/
│ │ ├── article-1/
│ │ │ ├── cover.jpg
│ │ │ └── index.md
│ │ └── article-2.md
│ └── 2023/
│ ├── article-3.md
│ └── article-4.md
├── products/ <-- 分類(頂層目錄)
│ ├── product-1/ <-- 分類(擁有 _index.md 檔案)
│ │ ├── benefits/ <-- 分類(擁有 _index.md 檔案)
│ │ │ ├── _index.md
│ │ │ ├── benefit-1.md
│ │ │ └── benefit-2.md
│ │ ├── features/ <-- 分類(擁有 _index.md 檔案)
│ │ │ ├── _index.md
│ │ │ ├── feature-1.md
│ │ │ └── feature-2.md
│ │ └── _index.md
│ └── product-2/ <-- 分類(擁有 _index.md 檔案)
│ ├── benefits/ <-- 分類(擁有 _index.md 檔案)
│ │ ├── _index.md
│ │ ├── benefit-1.md
│ │ └── benefit-2.md
│ ├── features/ <-- 分類(擁有 _index.md 檔案)
│ │ ├── _index.md
│ │ ├── feature-1.md
│ │ └── feature-2.md
│ └── _index.md
├── _index.md
└── about.md
上面的範例有兩個頂層分類:articles 和 products。articles 下的目錄都不是分類,而在 products 下的所有目錄都是分類。分類內的分類稱為嵌套分類或子分類。
解釋
分類和非分類在行為上有所不同。
分類 | 非分類 | |
---|---|---|
目錄名稱成為 URL 區段 | :heavy_check_mark: | :heavy_check_mark: |
有邏輯上的父類和子類關係 | :heavy_check_mark: | :x: |
有列表頁面 | :heavy_check_mark: | :x: |
使用 上面範例 的目錄結構:
-
articles 分類的列表頁面會包含所有文章,無論目錄結構如何;其中的子目錄都不是分類。
-
articles/2022 和 articles/2023 目錄並不擁有列表頁面;它們不是分類。
-
products 分類的列表頁面,預設會包含 product-1 和 product-2,但不包括它們的後代頁面。若要包含後代頁面,請在列表模板中使用
RegularPagesRecursive
方法,而不是Pages
方法。
- products 分類下的所有目錄都有列表頁面;每個目錄都是分類。
模板選擇
Hugo 有一套定義好的 查找順序 來確定在渲染頁面時使用哪個模板。這些 查找規則 會考慮頂層分類名稱;子分類名稱不會影響模板的選擇。
使用 上面範例 的目錄結構:
內容目錄 | 分類模板 |
---|---|
content/products | layouts/products/list.html |
content/products/product-1 | layouts/products/list.html |
content/products/product-1/benefits | layouts/products/list.html |
內容目錄 | 單一模板 |
---|---|
content/products | layouts/products/single.html |
content/products/product-1 | layouts/products/single.html |
content/products/product-1/benefits | layouts/products/single.html |
如果需要為子分類使用不同的模板,可以在前端資料中指定 type
和/或 layout
。
祖先和後代
分類有一個或多個祖先(包括首頁),以及零個或多個後代。使用 上面範例 的目錄結構:
content/products/product-1/benefits/benefit-1.md
該內容檔案(benefit-1.md)有四個祖先:benefits、product-1、products 和首頁。這種邏輯關係讓我們可以使用 .Parent
和 .Ancestors
方法來遍歷網站結構。
例如,使用 .Ancestors
方法來渲染麵包屑導航。
<nav aria-label="breadcrumb" class="breadcrumb">
<ol>
{{ range .Ancestors.Reverse }}
<li>
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
</li>
{{ end }}
<li class="active">
<a aria-current="page" href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
</li>
</ol>
</nav>
搭配這段 CSS:
.breadcrumb ol {
padding-left: 0;
}
.breadcrumb li {
display: inline;
}
.breadcrumb li:not(:last-child)::after {
content: "»";
}
Hugo 會渲染如下,每個麵包屑都是指向相應頁面的連結:
首頁 » 產品 » 產品 1 » 優勢 » 優勢 1