Does .GetPage have a sort filter?

I have a simple related section based on keywords

Frontmatter

keywords: ["a","b","c"]

In the template, I use

      {{ with .Params.keywords }}
      {{ range . }}
      {{ with site.GetPage (path.Join "/software/" .) }}

This lists the intended pages in ascending alpabetical order. Is there a way to either randomize these pages or return in a custom order for an example via date or other frontmatter ?

First, you can simplify your current code by eliminating the outer with statement. See documentation. Also note that path.Join inserts path separators for you.

{{ range .Params.keywords }}
  {{ with site.GetPage (path.Join "/software" .) }}
    <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a><br>
  {{ end }}
{{ end }}

Second, you can use the shuffle function to return a random permutation[1] of an array or slice. In this case, to defend against errors, you will need to wrap using the with statement.

{{ with .Params.keywords }}
  {{ range (shuffle .) }}
    {{ with site.GetPage (path.Join "/software" .) }}
      <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a><br>
    {{ end }}
  {{ end }}
{{ end }}

Third, to sort by a front matter field, build a slice of pages, then range through it.

{{ $pages := slice }}
{{ range .Params.keywords }}
  {{ with site.GetPage (path.Join "/software" .) }}
    {{ $pages = $pages | append . }}
  {{ end }}
{{ end }}
{{ range sort $pages "Params.foo" }}
  <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a><br>
{{ end }}

Finally, although the last example does what you have asked for, it does not allow you to use the built-in ordering methods such as ByWeight, ByDate, etc. Why? Because those methods are available to page collections, but not to generic slices.

So how do we create (and append to) an empty page collection? The first function allows you to create an empty array by setting the LIMIT argument to zero.

{{ $pages := first 0 site.Pages }}
{{ range .Params.keywords }}
  {{ with site.GetPage (path.Join "/software" .) }}
    {{ $pages = $pages | append . }}
  {{ end }}
{{ end }}
{{ range $pages.ByWeight }}
  <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a><br>
{{ end }}

  1. This generates a random list per build, not per site visit. ↩︎

2 Likes

Wow !

Thank you, Joe. You went above and beyond what I required. In the interim, I learned a lot from the final piece of code. Didn’t know you could shuffle just the dot. I kept passing the values of site.Getpage into a variable $t and did shuffle $t which obviously failed.

I guess I need to spend a bit more time on learning golang data structures.

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