| 1 |
--- |
| 2 |
_comment: Do not remove front matter. |
| 3 |
--- |
| 4 |
|
| 5 |
Hugo determines the _next_ and _previous_ page by sorting the page collection according to this sorting hierarchy: |
| 6 |
|
| 7 |
Field|Precedence|Sort direction |
| 8 |
:--|:--|:-- |
| 9 |
[`weight`][]|1|descending |
| 10 |
[`date`][]|2|descending |
| 11 |
[`linkTitle`][]|3|descending |
| 12 |
[`path`][]|4|descending |
| 13 |
|
| 14 |
The sorted page collection used to determine the _next_ and _previous_ page is independent of other page collections, which may lead to unexpected behavior. |
| 15 |
|
| 16 |
For example, with this content structure: |
| 17 |
|
| 18 |
```tree |
| 19 |
content/ |
| 20 |
├── pages/ |
| 21 |
│ ├── _index.md |
| 22 |
│ ├── page-1.md <-- front matter: weight = 10 |
| 23 |
│ ├── page-2.md <-- front matter: weight = 20 |
| 24 |
│ └── page-3.md <-- front matter: weight = 30 |
| 25 |
└── _index.md |
| 26 |
``` |
| 27 |
|
| 28 |
And these templates: |
| 29 |
|
| 30 |
```go-html-template {file="layouts/section.html"} |
| 31 |
{{ range .Pages.ByWeight }} |
| 32 |
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> |
| 33 |
{{ end }} |
| 34 |
``` |
| 35 |
|
| 36 |
```go-html-template {file="layouts/page.html"} |
| 37 |
{{ $pages := .CurrentSection.Pages.ByWeight }} |
| 38 |
|
| 39 |
{{ with $pages.Prev . }} |
| 40 |
<a href="{{ .RelPermalink }}">Previous</a> |
| 41 |
{{ end }} |
| 42 |
|
| 43 |
{{ with $pages.Next . }} |
| 44 |
<a href="{{ .RelPermalink }}">Next</a> |
| 45 |
{{ end }} |
| 46 |
``` |
| 47 |
|
| 48 |
When you visit page-2: |
| 49 |
|
| 50 |
- The `Prev` method points to page-3 |
| 51 |
- The `Next` method points to page-1 |
| 52 |
|
| 53 |
To reverse the meaning of _next_ and _previous_ you can chain the [`Reverse`][] method to the page collection definition: |
| 54 |
|
| 55 |
```go-html-template {file="layouts/page.html"} |
| 56 |
{{ $pages := .CurrentSection.Pages.ByWeight.Reverse }} |
| 57 |
|
| 58 |
{{ with $pages.Prev . }} |
| 59 |
<a href="{{ .RelPermalink }}">Previous</a> |
| 60 |
{{ end }} |
| 61 |
|
| 62 |
{{ with $pages.Next . }} |
| 63 |
<a href="{{ .RelPermalink }}">Next</a> |
| 64 |
{{ end }} |
| 65 |
``` |
| 66 |
|
| 67 |
> [!TIP] |
| 68 |
> If you also need the page's position within the collection, use the [`IndexOf`][] method instead. For example, use it to render "post 2 of 3" alongside the previous and next links. |
| 69 |
|
| 70 |
[`IndexOf`]: /methods/pages/indexof/ |
| 71 |
[`Reverse`]: /methods/pages/reverse/ |
| 72 |
[`date`]: /methods/page/date/ |
| 73 |
[`linkTitle`]: /methods/page/linktitle/ |
| 74 |
[`path`]: /methods/page/path/ |
| 75 |
[`weight`]: /methods/page/weight/ |