Limit number of posts in range

How can i limit the number of posts in the loop. like i want to show 10 posts but add a class to the first post only.

{{ range $k, $_ := where site.RegularPages "Type" "post" | first 10 }}
  {{ if $k }}
    <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
  {{ else }}
    <h2 class="first"><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
  {{ end }}
{{ end }}

For my own learning: am on my phone so haven’t been able to test this out yet.

But does this if statement work because the 0 key/index is considered falsy?

Yes…

1 Like
<div class="options ">
 
    {{ $paginator := .Paginate (where .Site.RegularPages "Section" "posts") }}
 
    {{ range  $index, $element := $paginator.Pages }}
 
     {{ if (eq $index 0 ) }}
      {{ $.Scratch.Set "classname" "active" }}
     {{ else }}
         {{ $.Scratch.Set "classname" "" }}

     {{ end }}
     <div class="option {{ $.Scratch.Get "classname" | safeHTML }}" style="--optionBackground:url({{.Site.BaseURL }}candidates/{{ .Params.image }});">
         <div class="shadow"></div>
         <div class="label">
            <div class="icon">
             <i class="fal fa-bell"></i>
            </div>
            <a  href="{{ .Permalink }}" title="{{ .Params.title }}" >
            <div class="info">
               <div class="main">{{ .Params.title }}</div>
               <div class="sub">{{ .Summary | truncate 50 }}</div>
            </div>
            </a>
         </div>
        </div>
    {{end}}
 </div>

this works but i need to limit the number of posts in case i have hundreds of posts.

See my previous comment, specifically the call to the first function.

thank you very much … your code works 100%

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