Enumerate posts

On my home page, I list all posts with

{{ range (.Paginator 10).Pages }}     
    <h2><a href="{{ .Permalink }}">{{ .Title }}</a></h2>
{{ end }}

I am aware that it is possible to add a date to each post, but what I would really like is to be able to add the number of the post. So the fourth post would be listed with “4.” before the title of the post.

Surely there is a way to do this but I could not find it in the documentation, in particular in the section on page variables:

Thanks in advance for any help.

Maybe using index on your range? This might be a hint:

The fourth post of what? Depending on what that is counting, there are different ways to generate the number.

The only issue I see there is that I am also using pagination, so I could enumerate the posts on a particular page, but the numbers would restart on each page.

I was thinking of the order in terms of the date of the post. However, if there is some other way to attach a number to each post, I would be interested.

Okay, success.

Define the paginator beforehand with

{{ $paginator := .Paginate (where .Data.Pages "Type" "post") }}

Then the number for the first post on the page is given by

{{ $startcount := sub $paginator.TotalNumberOfElements (mul $paginator.PageSize (sub $paginator.PageNumber 1)) }}

Finally, when looping over the posts use an index and prefix each post with {{ sub $startcount $index }} as follows

{{ range $index, $element := $paginator.Pages }}     
    <h2><a href="{{ .Permalink }}">
    {{ sub $startcount $index }}.
    {{ .Title }}</a></h2>
{{ end }}

Thanks to Rick for leading me to a solution.

4 Likes