Search code examples
gohugogo-html-template

Combining first function with index in golang/html template


I'm creating a blog with Hugo. i would like to list the first 3 Blog entries. That is not a problem so far.

{{ range first 3 .Data.Pages.ByPublishDate }}

But i need the index for adding css classes. I do that with this line

{{ range $index, $element := .Data.Pages.ByPublishDate }}

My problem now is how following. How do I get the index like in the second line of code but still limit the result to 3.

Unfortunately this doesn't seem to work.

{{ range first 3 $index, $element := .Data.Pages.ByPublishDate }}

Any ideas?


Solution

  • I think what you are looking for based on your examples is the following:

    {{ range $index, $element := (first 3 .Data.Pages.ByPublishDate) }}