Debian Codegraph @

docs/content/en/_common/methods/page/nextinsection-and-previnsection.md

raw
1 ---
2 _comment: Do not remove front matter.
3 ---
4
5 Hugo determines the _next_ and _previous_ page by sorting the current section's regular pages 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 {{ with .PrevInSection }}
38 <a href="{{ .RelPermalink }}">Previous</a>
39 {{ end }}
40
41 {{ with .NextInSection }}
42 <a href="{{ .RelPermalink }}">Next</a>
43 {{ end }}
44 ```
45
46 When you visit page-2:
47
48 - The `PrevInSection` method points to page-3
49 - The `NextInSection` method points to page-1
50
51 To reverse the meaning of _next_ and _previous_ you can change the sort direction in your [project configuration][], or use the [`Next`][] and [`Prev`][] methods on a `Pages` object for more flexibility.
52
53 ## Example
54
55 Code defensively by checking for page existence:
56
57 ```go-html-template
58 {{ with .PrevInSection }}
59 <a href="{{ .RelPermalink }}">Previous</a>
60 {{ end }}
61
62 {{ with .NextInSection }}
63 <a href="{{ .RelPermalink }}">Next</a>
64 {{ end }}
65 ```
66
67 ## Alternative
68
69 Use the [`Next`][] and [`Prev`][] methods on a `Pages` object for more flexibility.
70
71 [`Next`]: /methods/pages/next/
72 [`Prev`]: /methods/pages/prev/
73 [`date`]: /methods/page/date/
74 [`linkTitle`]: /methods/page/linktitle/
75 [`path`]: /methods/page/path/
76 [`weight`]: /methods/page/weight/
77 [project configuration]: /configuration/page/