PrevInSection
Syntax
PAGE.PrevInSection
Returns
page.Page
Hugo 通过根据以下排序层次对当前章节的常规页面进行排序来确定 next 和 previous 页面:
字段 | 优先级 | 排序方向 |
---|---|---|
weight |
1 | 降序 |
date |
2 | 降序 |
linkTitle |
3 | 降序 |
path |
4 | 降序 |
用于确定 next 和 previous 页面的已排序页面集合独立于其他页面集合,这可能会导致意外行为。
例如,使用以下内容结构:
content/
├── pages/
│ ├── _index.md
│ ├── page-1.md <-- front matter: weight = 10
│ ├── page-2.md <-- front matter: weight = 20
│ └── page-3.md <-- front matter: weight = 30
└── _index.md
以及这些模板:
layouts/_default/list.html
{{ range .Pages.ByWeight }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
layouts/_default/single.html
{{ with .PrevInSection }}
<a href="{{ .RelPermalink }}">Previous</a>
{{ end }}
{{ with .NextInSection }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
当您访问 page-2 时:
PrevInSection
方法指向 page-3NextInSection
方法指向 page-1
要反转 next 和 previous 的含义,您可以更改 站点配置 中的排序方向,或者在 Pages
对象上使用 Next
和 Prev
方法以获得更大的灵活性。
示例
通过检查页面是否存在来防御性地编写代码:
{{ with .PrevInSection }}
<a href="{{ .RelPermalink }}">Previous</a>
{{ end }}
{{ with .NextInSection }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}