Attempting to display five upcoming events sorted by a custom front matter param, start_date:
{{ $events := where .Site.RegularPages "Section" "events" }}
{{ $events = sort $events ".Params.start_date" "asc" }}
{{ $events = where $events (time .Params.start_date).Unix "gt" now.Unix }}
{{ range first 5 $events }}
{{ partial "event/card.html" . }}
{{ end }}
This results in an error:
execute of template failed at <time .Params.start_date>: error calling time: unable to cast <nil> of type <nil> to Time
Without using first, I’m able to display all upcoming events with the following:
{{ $all_events := where .Site.RegularPages "Section" "events" }}
{{ range (sort $all_events ".Params.start_date" "asc") }}
{{ $start := (time .Params.start_date).Unix }}
{{ $now := now.Unix }}
{{ if (gt $start $now) }}
{{ partial "event/card.html" . }}
{{ end }}
{{ end }}
But this doesn’t allow for showing only the first 5.
What am I doing wrong?
Is your front matter YAML, TOML, or JSON?
Please provide front matter example that shows how start_date is formatted, and confirm that all start_date values are consistently formatted.
All are formatted identically as follows, (yyyy-mm-dd):
start_date: 2023-09-19
No missing values.
{{/* Build slice of future events. */}}
{{ $p := slice }}
{{ range where site.RegularPages "Section" "events" }}
{{ if (.Params.event_date | time.AsTime).After now }}
{{ $p = $p | append . }}
{{ end }}
{{ end }}
{{/* Sort and show the first 5. */}}
{{ range sort $p "Params.event_date" | first 5 }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
And that’s why I prefer TOML front matter.
With TOML, date values are first-class citizens. TOML has a date data type while JSON and YAML do not. When you add a custom date field to your TOML front matter, the value is already of type time.Time and does not require conversion.
Thank you! Once again, you have saved the day 
I didn’t know this about TOML vs YAML front matter. Much appreciated!