I am trying to get the sorted string values of keys from a list of key-value pairs:
<div>
{{ range $key, $value := sort .Params.buttons "value" "asc"}}
<a class="button" href="{{ $key }}" role="button">{{ $value }}</a>
{{ end }}
</div>
Here is the frontmatter for that page:
buttons:
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?
zwbetz
January 23, 2019, 3:27pm
2
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 .
1 Like
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?
zwbetz
January 24, 2019, 4:51pm
4
Yep. Don’t store your data in keys. Use a map instead:
---
buttons:
- 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!