Can't get value of key when ranging through sorted keys

I am trying to get the sorted string values of keys from a list of key-value pairs:

{{ range $key, $value := sort .Params.buttons "value" "asc"}}
       <a class="button" href="{{ $key }}" role="button">{{ $value }}</a>
{{ end }}

Here is the frontmatter for that page:

  url1: text1 
  url2: text2
  url3: text3

Instead of getting ‘url1’, ‘url2’, etc. when using {{ $keys }}, all I get is the index values (0, 1, 2, etc.). This doesn’t happen when I leave out the sorting:

{{ range $key, $value := .Params.buttons}}

Any hint?

Hi @theletterf,

You may not want to hear this, but per the sort docs:

A sorted array of map values will be returned with the keys eliminated.

Oh no. :-/

How could I sort whatever comes out of {{ range $key, $value := .Params.buttons}}then?

Should I use a different data structure in the frontmatter?

Yep. Don’t store your data in keys. Use a map instead:

  - url: url1
    text: text1
  - url: url3
    text: text3
  - url: url2
    text: text2

Then this template code:

{{ range sort .Params.buttons ".url" }}
url = {{ .url }}
text = {{ .text }}
{{ end }}

Will output:

url = url1
text = text1

url = url2
text = text2

url = url3
text = text3
1 Like

Worked like a charm. Thanks, Zachary!