Sort RegularPages by param B if param A is empty / not present

I have this block in a page layout:

{{- $sortedPages := (site.RegularPages.ByParam "Date").Reverse -}}

This returns pages in descending order. What I want to do is introduce a second param from the front matter that will take precedence if it is present. What I tried to do was this:

{{- $sortedPages := (sort site.RegularPages (default .Params.Date .Params.RenewedDate) "desc") -}}

Assuming that where RenewedDate is present in the front matter it will be used instead of the date but this doesn’t seem to do what I want, instead the pages remain in the same order as the original block.

Is there a way to do this?

Thanks!

Is your front matter TOML?

Currently it is YAML but I’m not precious about it…

TOML is always a better choice when you have custom date parameters.

With TOML, date values are first-class citizens. TOML has a date data type while JSON and YAML do not. If you quote a TOML date, it is a string. If you do not quote a TOML date value, it is a time.Time value, enabling precise comparisons.

Note that the four predefined front matter dates are cast to time.Time values regardless of front matter format.

You can’t use functions within the sort function’s first argument. Instead, you can build a slice of maps, where each map has two keys: sortDate and page.

  {{ $p := slice }}
  {{ range site.RegularPages }}
    {{ $p = $p | append (dict "sortDate" (or .Params.renewedDate .Date) "page" .) }}
  {{ end }}

  {{ range sort $p "sortDate" "desc" }}
    <h2>{{ .page.Title }}</h2>
    <p>sortDate = {{ .sortDate }}</p>
    <p>date = {{ .page.Date }}</p>
    <p>renewedDate = {{ .page.Params.renewedDate }}</p>
  {{ end }}
1 Like

Brilliant, that has done the trick. Fortunately not too many pages to fix up!

Thanks for the help.

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