IndexOf
返回给定页面在给定页面集合中从零开始的索引。
(0.166.0 新增)
如果给定的页面不在页面集合中,IndexOf 方法返回 -1。
有如下内容结构:
content/
├── posts/
│ ├── _index.md
│ ├── post-1.md <-- front matter: weight = 10
│ ├── post-2.md <-- front matter: weight = 20
│ └── post-3.md <-- front matter: weight = 30
└── _index.md以及这个模板:
{{ $pages := .CurrentSection.Pages.ByWeight }}
{{ $index := add ($pages.IndexOf .) 1 }}
<p>This is post {{ $index }} of {{ $pages.Len }} in {{ .CurrentSection.LinkTitle }}.</p>访问 post-2 时,Hugo 渲染为:
<p>This is post 2 of 3 in Posts.</p>也可以用 IndexOf 方法构建「上一个/下一个」导航链接。结合 index 与 add/sub 函数,可以用它取得同一页面集合中的上一个和下一个页面:
{{ $pages := .CurrentSection.Pages.ByWeight }}
{{ $index := $pages.IndexOf . }}
{{ if ge $index 0 }}
{{ with index $pages (add $index 1) }}
<a href="{{ .RelPermalink }}">Previous</a>
{{ end }}
{{ with index $pages (sub $index 1) }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
{{ end }}{{ $pages := .CurrentSection.Pages.ByWeight }}
{{ with $pages.Prev . }}
<a href="{{ .RelPermalink }}">Previous</a>
{{ end }}
{{ with $pages.Next . }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}