Can I call .Pages.ByLength using the string "ByLength"? E.g. (index .Pages "ByLength") doesn't work

I want to define the sorting of pages in a list using a data file (therefor using a “string”), but have some issues.

{{ range .Pages }} is the default sort, I can also do {{ range (.Pages.ByParam $data_param) }}, and all is well… but what if I want to sort by ByExpiryDate, ByLength, or ByLinkTitle, which have no ByParam equivalent?

I tried {{ range (index .Pages "ByLength") }} or {{ range (index .Pages $data_by) }} but index doesn’t support methods/functions (?).


One solution would be to just spell out every .By* function in the template and call the appropriate one given the data string, but that’s allot more template code and it doesn’t automatically support every .By* function that may appear in Hugo at a later date. I could do this but perhaps there is a better solutions?

{{ if eq $data_by "ByLength" }}
    {{ range .Pages.ByLength }}
        ...
    {{ end }}
{{ else if eq $data_by "ByExpiryDate" }}
...

Most Relevant Docs

Not a solution, but you can shorten the template code like this:

{{ $pageRanges := dict "ByLength" .Pages.ByLength "ByExpiryDate" .Pages.ByExpiryDate }}
{{ range (index $pageRanges $data_by) | default (.Pages.ByParam $data_by) }}
  ...
{{ end }}

Not sure about the performance though. Maybe someone knows if sorted page cache is populated during access or iteration (range).

It seems that since the .Pages is an array, the go template engine expects int keys with index. We would need a new Hugo template function to allow access to Page functions by string.

1 Like