PrevInSection

Hugo 根據以下排序層級,針對當前區段的常規頁面決定下一頁上一頁

欄位 優先順序 排序方向
weight 1 降冪
date 2 降冪
linkTitle 3 降冪
path 4 降冪

用於決定下一頁上一頁的排序頁面集合,與其他頁面集合獨立運作,這可能導致意料之外的行為。

例如,考慮以下內容結構:

content/
├── pages/
│   ├── _index.md
│   ├── page-1.md   <-- 前置內容:weight = 10
│   ├── page-2.md   <-- 前置內容:weight = 20
│   └── page-3.md   <-- 前置內容: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 }}">上一頁</a>  
{{ end }}  

{{ with .NextInSection }}  
  <a href="{{ .RelPermalink }}">下一頁</a>  
{{ end }}  

當您瀏覽 page-2 時:

  • PrevInSection 方法指向 page-3
  • NextInSection 方法指向 page-1

若要反轉下一頁上一頁的意義,您可以在站點設定中修改排序方向,或者在 Pages 物件上使用 NextPrev 方法以取得更多彈性。

範例

在程式碼中防禦性地檢查頁面是否存在:

{{ with .PrevInSection }}
  <a href="{{ .RelPermalink }}">上一頁</a>
{{ end }}

{{ with .NextInSection }}
  <a href="{{ .RelPermalink }}">下一頁</a>
{{ end }}

替代方案

對於更多彈性,使用 Pages 物件上的 NextPrev 方法。