collections.Shuffle
Returns a random permutation of a given array or slice.
Syntax
collections.Shuffle COLLECTION
Returns
any
Alias
shuffle
{{ collections.Shuffle (seq 1 2 3) }} → [3 1 2]
{{ collections.Shuffle (slice "a" "b" "c") }} → [b a c]
The result will vary from one build to the next.
To render an unordered list of 5 random pages from a page collection:
<ul>
{{ $p := site.RegularPages }}
{{ range $p | collections.Shuffle | first 5 }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
For better performance with large collections, use the math.Rand
and collections.Index
functions instead:
<ul>
{{ $p := site.RegularPages }}
{{ range seq 5 }}
{{ with math.Rand | mul $p.Len | math.Floor | int }}
{{ with collections.Index $p . }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
{{ end }}
{{ end }}
</ul>