Sort YML as resource descending

Hi all!

I have a seemingly simple problem and I may just be missing something simple, so I’m hoping someone can help.

I have a yaml file that looks like this:

pub.yml:

2022:
    - a line of text
    - another line of text
2021:
    - old and busted
    - stuff from last year
...
2015:
    - really old
    - older stuff

This is a file in my page bundle that I can access using code like:

{{ with .Resources.GetMatch "pub.yml" }}

        {{ $data := . | transform.Unmarshal }}
          {{ range $index, $value := $data }}

            <h3>{{ $index }}</h3>

            {{ range $value }}
            <p>{{ . }}</p>
            {{ end }}

          {{ end }}

{{ end }}

This works as expected wonderfully, except that the output is sorted by the first key, ascending (2015, …, 2021, 2022).

How can I sort by the key descending? (2015, …, 2021, 2022)

With that data structure you have to jump through some hoops…

{{ with .Resources.GetMatch "pub.yml" }}
  {{ with $data := transform.Unmarshal . }}

    {{/* Get slice of keys, sorted descending. */}}
    {{ $keys := slice }}
    {{ range $k, $_ := $data }}
      {{ $keys = $keys | append $k }}
    {{ end }}
    {{ $keys = sort $keys "value" "desc" }}

    {{/* Render. */}}
    {{ range $keys }}
      <h2>{{ . }}</h2>
      {{ range index $data . }}
        {{ . }}<br>
      {{ end }}
    {{ end }}
    
  {{ end }}
{{ end }}

1 Like

Oof. I’m open to suggestions for an easier data structure if it makes sense (and will be simple enough for a user to modify the yaml).

And thank you for this!
[edit: worked like a charm! :+1:]

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