Reverse Array

layouts/partials/reverse-slice.html

{{- $sliceOriginal := . -}}
{{- $len := len $sliceOriginal -}}
{{- $sliceReversed := slice -}}
{{- range seq $len -}}
  {{- $sliceReversed = $sliceReversed | append (index $sliceOriginal (sub $len .)) }}
{{- end -}}
{{- return $sliceReversed -}}

Then call the partial from a template or shortcode:

{{- $myArray := slice "c" "b" "a" -}}
{{- $myArrayReversed := partial "reverse-slice.html" $myArray -}}

Reference:
https://discourse.gohugo.io/t/how-to-reverse-sort-frontmatter-list/23442/10

3 Likes