Send variable value to single.html


Here is my list.html:

{{ $pages := .Pages.ByDate.Reverse }}
{{ $numberPages := len $pages }}
{{ range $index, $page := $pages }}
  {{ $pageIndex := sub $numberPages $index }}

The value of $pageIndex depends on page in the range. How can I access the value of $pageIndex in each corresponding single.html page?

I am open to any kind of solution, as I am not sure what the most idiomatic thing would be.


A little context would be helpful. What you are trying to do?

Thank you for asking.

My website is like a blog. The template list.html lists the blog entries, and the variable $pageIndex stores the number of each entry. In the end, the list page renders something like

3: Hugo is great
2: I love HTML
1: My first post

The thing I want to do is to get this page number in the single.html page of each entry.

Does that make sense?

Again, why?

Sorry for not being clear. I want this number to be printed along side the title of each blog entry, inside the blog entry.

A given page is rendered once, and pages are rendered in parallel. To get what you want, you would need to place something like this in your single page template:

{{ $n := 0 }}
{{ range $k, $_ := (where site.RegularPages "Section" "posts").ByDate.Reverse }}
  {{ if $.Eq . }}
    {{ $n = add $k 1 }}
    {{ break }}
  {{ end }}
{{ end }}

<p>This is page {{ $n }}.</p>

If your site has 100 pages this is not a significant performance hit. But if your site has 50,000 pages, this could result in as many as 2.5 billion iterations.

1 Like

Works like a charm (except the break, which I had to remove), thanks!

Instead of removing important code, perhaps you should be using a current version of Hugo.

The debian package is not up to date.

When you install from a distro’s package repo, you are typically locked to what was available at time of the distro’s release. That behavior is not specific to Hugo.

Use another installation method.

I highly recommend to install Hugo from the prebuilt binaries from the releases page on GitHub (Release v0.111.3 · gohugoio/hugo · GitHub), it’s always efficient! (I’m a Linux user of Hugo too.)

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.