content: Document alternative to shuffle for large collections

This commit is contained in:
Joe Mooring 2025-05-05 16:01:46 -07:00 committed by GitHub
parent 7fe42d76cf
commit 5ef94a725e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -12,8 +12,37 @@ aliases: [/functions/shuffle]
---
```go-html-template
{{ shuffle (seq 1 2 3) }} → [3 1 2]
{{ shuffle (slice "a" "b" "c") }} → [b a c]
{{ 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:
```go-html-template
<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:
```go-html-template
<ul>
{{ $p := site.RegularPages }}
{{ range seq 5 }}
{{ with math.Rand | mul $p.Len | math.Floor | int }}
{{ with index $p . }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
{{ end }}
{{ end }}
</ul>
```
[`collections.Index`]:/functions/collections/indexfunction/
[`math.Rand`]: /functions/math/rand/