[SOLVED] Adding different class names to each post within a range

Using Hugo, I need add unique class names to the first few posts. How can this be done?

My code that’s obviously not working…

// if the first post
{{ if eq .Site.GetPage 1 }}
    {{ $classname := "class-one" }}
// else the second post
{{ elseif eq .Site.GetPage 2 }}
    {{ $classname := "class-two" }}
// else the third post
{{ elseif eq .Site.GetPage 3 }}
    {{ $classname := "class-three" }}
{{ else }}
{{ $classname := "" }}
{{ end }}

<li class="{{ $classname }}">
    …
</li>

You need to use .Scratch :slight_smile:

1 Like

I tried using Scratch before, and it made no difference. Besides, I think my if statement is wrong.
I’ve tried: {{ if eq .Site.GetPage 1 }} as well as {{ if eq .Data.Pages 1 }}

How do you exactly target the first, second, etc., page items inside a range? Do I need to add an $index to the range? How exactly?

Current code:

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

{{ if eq .Data.Pages 1 }}
  {{ .Scratch.Set "classname" "class-one" }}
{{ elseif eq .Data.Pages 2 }}
  {{ .Scratch.Set "classname" "class-two" }}
{{ end }}

<li class="{{ .Scratch.Get "classname" | safeHTML }}">
    …
</li>

{{ end }}

Figured it out, I think…

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

{{ range $index, $element := $paginator.Pages }}

{{ if (eq $index 0) }}
{{ $.Scratch.Set "classname" "class-one" }}
{{ else if (eq $index 1) }}
{{ $.Scratch.Set "classname" "class-two" }}
{{ else }}
{{ $.Scratch.Set "classname" "" }}
{{ end }}

<li class="{{ $.Scratch.Get "classname" | safeHTML }}">
    …
</li>

{{ end }}

A post was split to a new topic: Limit number of posts in range