Shuffle on .Site.Data - can't iterate over map[string]interface {}


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.

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.


oh yeah…
So how would you turn a map into an array ? (golang newbie here)


I am newbie to Golang as well :slightly_smiling:

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 }}

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

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) }}

Hugo is a static site generator, so new random seed on every hugo builds sounds about right.

A post was split to a new topic: List random content