| 1 |
--- |
| 2 |
title: IndexOf |
| 3 |
description: Returns the zero-based index of the given page within the given page collection. |
| 4 |
categories: [] |
| 5 |
keywords: [] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
returnType: int |
| 9 |
signatures: [PAGES.IndexOf PAGE] |
| 10 |
--- |
| 11 |
|
| 12 |
{{< new-in 0.166.0 />}} |
| 13 |
|
| 14 |
If the given page is not in the page collection, the `IndexOf` method returns `-1`. |
| 15 |
|
| 16 |
With this content structure: |
| 17 |
|
| 18 |
```tree |
| 19 |
content/ |
| 20 |
├── posts/ |
| 21 |
│ ├── _index.md |
| 22 |
│ ├── post-1.md <-- front matter: weight = 10 |
| 23 |
│ ├── post-2.md <-- front matter: weight = 20 |
| 24 |
│ └── post-3.md <-- front matter: weight = 30 |
| 25 |
└── _index.md |
| 26 |
``` |
| 27 |
|
| 28 |
And this template: |
| 29 |
|
| 30 |
```go-html-template {file="layouts/posts/page.html"} |
| 31 |
{{ $pages := .CurrentSection.Pages.ByWeight }} |
| 32 |
{{ $index := add ($pages.IndexOf .) 1 }} |
| 33 |
<p>This is post {{ $index }} of {{ $pages.Len }} in {{ .CurrentSection.LinkTitle }}.</p> |
| 34 |
``` |
| 35 |
|
| 36 |
When you visit post-2, Hugo renders: |
| 37 |
|
| 38 |
```html |
| 39 |
<p>This is post 2 of 3 in Posts.</p> |
| 40 |
``` |
| 41 |
|
| 42 |
You can also use the `IndexOf` method to build previous and next navigation links. Combined with the [`index`][] and [`add`][]/[`sub`][] functions, use it to get the previous and next page in the same page collection: |
| 43 |
|
| 44 |
```go-html-template |
| 45 |
{{ $pages := .CurrentSection.Pages.ByWeight }} |
| 46 |
{{ $index := $pages.IndexOf . }} |
| 47 |
|
| 48 |
{{ if ge $index 0 }} |
| 49 |
{{ with index $pages (add $index 1) }} |
| 50 |
<a href="{{ .RelPermalink }}">Previous</a> |
| 51 |
{{ end }} |
| 52 |
|
| 53 |
{{ with index $pages (sub $index 1) }} |
| 54 |
<a href="{{ .RelPermalink }}">Next</a> |
| 55 |
{{ end }} |
| 56 |
{{ end }} |
| 57 |
``` |
| 58 |
|
| 59 |
This is equivalent to using the [`Prev`][] and [`Next`][] methods: |
| 60 |
|
| 61 |
```go-html-template |
| 62 |
{{ $pages := .CurrentSection.Pages.ByWeight }} |
| 63 |
|
| 64 |
{{ with $pages.Prev . }} |
| 65 |
<a href="{{ .RelPermalink }}">Previous</a> |
| 66 |
{{ end }} |
| 67 |
|
| 68 |
{{ with $pages.Next . }} |
| 69 |
<a href="{{ .RelPermalink }}">Next</a> |
| 70 |
{{ end }} |
| 71 |
``` |
| 72 |
|
| 73 |
> [!TIP] |
| 74 |
> Unlike `Prev` and `Next`, the `IndexOf` approach also gives you the page's position within the collection, as shown in the example at the beginning of this page. |
| 75 |
|
| 76 |
[`Next`]: /methods/pages/next/ |
| 77 |
[`Prev`]: /methods/pages/prev/ |
| 78 |
[`add`]: /functions/math/add/ |
| 79 |
[`index`]: /functions/collections/indexfunction/ |
| 80 |
[`sub`]: /functions/math/sub/ |