Ranging over collection of data files

A good nights sleep helped to think about this.

range accepts maps, arrays and slices, first and where only accept an array or a slice.

The data in the data/ folder will be accessible as a map in the .Site.Data variable. A map by Golang definitions is an unordered container for data, the order within that container is quite random.
Posts in the content/ folder on the other side will be parsed into a slice of type Pages []*Page with a default order Default: Weight > Date > LinkTitle > FilePath, if not defined otherwise.

This makes sense in the context of first, as you want to reliably retrieve the first n elements of a slice. As the content of a map is rather random, first would do the same as any (if that function would exist), as you don’t know which elements come back. I don’t understand, why where would need a sorted data array, as a mixed map would suffice, but that is another topic.

And here comes sort to the rescue, which sorts maps, arrays, and slices and returns a sorted slice. Try sorting the data first before filtering:

{{ range first 2 (sort .Site.Data.articles) }}
    <p>Title: {{ .title }}</p>
{{ end }}
{{ $sorted := sort .Site.Data.articles }}
{{ range where $sorted "author" "Lewis" }}
    <p>Title: {{ .title }}</p>
{{ end }}

:raised_hands:

7 Likes