Range starting from index k?

I’m iterating through 9 of the most recent posts and putting them into a div grid:

<section class="recent-posts">
	{{ $i := 0 }}
	{{ range first 9 .Pages.ByLastmod.Reverse }}
	    {{ $i = add $i 1 }}
	    <div class="rpost{{ $i }}">{{ .Title }}</div>
	{{ end }}
</section>

I wish to put the rest of older posts into a separate section.

What syntax should I use to iterate through the collection of .Pages.ByLastmod.Reverse where index is ≥ 9?

Thanks @jmooring, this does the job.

However, I do have a problem. My current code is:

{{ $posts := .Pages }}
{{ $nposts := len $posts }}
{{ $nposts := sub $nposts 9 }}
<h1>{{ $nposts }}</h1>
{{ range first 999 (after 9 .Pages.ByLastmod.Reverse) }}
	<p>{{ .Title }}</p>
{{ end }}

<h1> is for debugging.

If I replace 999 with $nposts, which I assume stores an integer, or at least it prints out like one in <h1>, I get the following error:

executing "main" at <first $nposts (after 9 .Pages.ByLastmod.Reverse)>: error calling first: sequence length must be non-negative

Which is strange, since $nposts is a positive number that defines the number of posts minus those 9 that are rendered in the previous section. Unless I messed something up.

I tried casting $nposts to int, but the result is the same.

First, I think you can replace all of your code with:

{{ range after 9 .Pages.ByLastmod.Reverse }}
  <p>{{ .Title }}</p>
{{ end }}

Second, with 9 or more published (not draft or future) pages, I cannot reproduce the error. With fewer than 9 pages, $nposts is a negative number, and first -n is nonsensical.

If your code is in a template used by multiple sections, each section must have 9 or more pages to avoid the error.

1 Like

You’re absolutely right, I overcomplicated this. range after 9 works perfectly.
Thanks again.

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