Custom Sorting PageGroups

Is there a way to sort groups created using .Pages.GroupByParam based on a parameter?
I’m aware of OrderBy argument, but that only seems to be asc or desc. I need more control over the order of groups.

{{ range .Pages.GroupByParam "group_name" "asc" }}
      <h3>{{ .Key }}</h3>
      {{- partial "group-content" . -}}
{{ end }}

Code above returns groups in alphabetical order: ["aaa-group" ,... "zzz-group"]
I want to be able to order these based on some weight defined as $groups_weights := dict("aaa-group" 5 "bbb-group" 20 ...)
Any ideas?

Things I’ve tried

{{ $groups := (.Pages.GroupByParam "group_name" )}}
{{ range sort $groups (index $groups_weights .Key) }}
       <h3>{{ .Key }}</h3>
       {{- partial "group-content" . -}}
{{ end }}

I get error: can't evaluate field Key in type *hugolib.pageState

I figured second parameter on sort needs to be a PageGroup property. so I tried to attach the weight to pageGroup in a separate loop but doesn’t seem to work either.

{{ range $groups }}
  {{ .newWeight := (index $groups_weights .Key) }}
{{ end }}
{{ range sort $groups "newWeight"}}
  <h3>{{ .Key }}</h3>
  {{- partial "group-content" . -}}
{{ end }}

The following examples assume an optional front matter field named group_name with a value of a, b, c.

Method 1

{{ $groups := site.RegularPages.GroupByParam "group_name" }}
{{ $group_order := slice "b" "a" "c" }}
{{ range $group_order }}
  {{ with index (where $groups "Key" .) 0 }}
    <h3>{{ .Key }}</h3>
    {{ range .Pages }}
      <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a><br>
    {{ end }}
  {{ end }}
{{ end }}

Method 2

{{ $groups := slice "b" "a" "c" }}
{{ range $group := $groups }}
  {{ with where site.RegularPages "Params.group_name" $group }}
    <h3>{{ $group }}</h3>
    {{ range . }}
      <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a><br>
    {{ end }}
  {{ end }}
{{ end }}

If you have a Very Large Site and are concerned about performance, I suspect the first method is faster, but I could be wrong.

2 Likes

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