Hugo Sections
将内容组织成 sections。
概述
section(节)是顶级内容目录或任何包?_index.md 文件的内容目录
content/
├── articles/ <-- section(顶层目录)
│ ├── 2022/
│ │ ├── article-1/
│ │ │ ├── cover.jpg
│ │ │ └── index.md
│ │ └── article-2.md
│ └── 2023/
│ ├── article-3.md
│ └── article-4.md
├── products/ <-- section(顶层目录)
│ ├── product-1/ <-- section(有 _index.md 文件)
│ │ ├── benefits/ <-- section(有 _index.md 文件)
│ │ │ ├── _index.md
│ │ │ ├── benefit-1.md
│ │ │ └── benefit-2.md
│ │ ├── features/ <-- section(有 _index.md 文件)
│ │ │ ├── _index.md
│ │ │ ├── feature-1.md
│ │ │ └── feature-2.md
│ │ └── _index.md
│ └── product-2/ <-- section(有 _index.md 文件)
│ ├── benefits/ <-- section(有 _index.md 文件)
│ │ ├── _index.md
│ │ ├── benefit-1.md
│ │ └── benefit-2.md
│ ├── features/ <-- section(有 _index.md 文件)
│ │ ├── _index.md
│ │ ├── feature-1.md
│ │ └── feature-2.md
│ └── _index.md
├── _index.md
└── about.md上面的示例有两个顶层 sections:articles 和 products。articles 下的目录都不是 sections,而 products 下的所有目录都是 sections。section 内的 section 称为嵌套 section 或子 section。
说明
sections 和非 sections 的行为不同。
| Sections | Non-sections | |
|---|---|---|
| 目录名称成为 URL 段 | ✔️ | ✔️ |
| 有逻辑上的祖先和后代 | ✔️ | ❌ |
| 有列表页面 | ✔️ | ❌ |
使用 上面示例 中的文件结构:
- articles section 的列表页面包括所有文章,无论目录结构如何;子目录都不是 sections。
- articles/2022 和 articles/2023 目录没有列表页面;它们不是 sections。
- products section 的列表页面默认包括 product-1 和 product-2,但不包括它们的后代页面。要包括后代页面,在 section 模板中使用
RegularPagesRecursive方法而不是Pages方法。 - products section 中的所有目录都有列表页面;每个目录都是 section。
模板选择
Hugo 有定义的 lookup order 来确定渲染页面时使用哪个模板。lookup rules 考虑顶层 section 名称;选择模板时不考虑子 section 名称。
使用 上面示例 中的文件结构:
| Content directory | Section template |
|---|---|
content/products |
layouts/products/section.html |
content/products/product-1 |
layouts/products/section.html |
content/products/product-1/benefits |
layouts/products/section.html |
| Content directory | Page template |
|---|---|
content/products |
layouts/products/page.html |
content/products/product-1 |
layouts/products/page.html |
content/products/product-1/benefits |
layouts/products/page.html |
如果你需要为子 section 使用不同的模板,在 front matter 中指定 type 和/或 layout。
祖先和后代
section 有一个或多个祖先(包括首页),以及零个或多个后代。使用 上面示例 中的文件结构:
content/products/product-1/benefits/benefit-1.md内容文件(benefit-1.md)有四个祖先:benefits、product-1、products 和首页。这种逻辑关系允许我们使用 .Parent 和 .Ancestors 方法遍历站点结构。
例如,使用 .Ancestors 方法渲染面包屑导航。
layouts/_partials/breadcrumb.html
<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 渲染这个,每个面包屑都是相应页面的链接:
Home » Products » Product 1 » Benefits » Benefit 1