Hello,
I tried to look for a solution without success, so I am posting my issue here.
I have data objects store in /data/product
I want to randomly display 6 of those products on a page.
I was thinking of using something like:
{{ range .Site.Data.product | shuffle | first 6 }} {{ partial "product/li" . }} {{ end }}
But it gives me the following error
executing “theme/partials/portfolio.html” at : error calling shuffle: can’t iterate over map[string]interface {} in theme/partials/portfolio.html
Not sure how to solve that… I tried all type of combinations, in different orders.
If you have hints, that would help a lot.
Thanks
sairam
November 2, 2016, 6:27pm
2
shuffle returns a random permutation of a given array or slice
shuffle only works for array or slice . Looks like you have a map here.
source: https://gohugo.io/templates/functions/
oh yeah…
So how would you turn a map into an array ? (golang newbie here)
thanks
sairam
November 2, 2016, 6:46pm
4
I am newbie to Golang as well
I was trying to find the length and generate random numbers using sequence.
But need to find element at index with the following which can solve your problem.
{{ $len := .Site.Data.product | len }}
{{ range $d := first 6 (shuffle (seq $len )) }}
{{ $d }}
{{ end }}
bep
November 2, 2016, 7:00pm
5
You will have to look at your data file vs the spec for the format you use and get your products represented as a list/array and not a map.
1 Like
sairam
November 2, 2016, 7:04pm
6
You can’t use shuffle
since it returns the same array of elements (Guessing it uses math/random
) because of the seed value initiated at run time by hugo.
Try this out without restarting the server, you will get the same sequence every time (till restart)
{{ shuffle (seq 1 5) }}
bep
November 2, 2016, 7:41pm
7
Hugo is a static site generator, so new random seed on every hugo builds sounds about right.
pointyfar
Split this topic
August 26, 2020, 11:19am
8
A post was split to a new topic: List random content