juh
1
Hi all,
I want to colorize my blog by selecting colors randomly.
So I created a data file colorschemes.yaml
where I define a list of color combinations like this: color:bgcolor
combinations:
- dark-red: white
- black: white
- gold: white
From this list I want to select one combination randomly and put it somewhere in my html:
<div class="$color $bgcolor">Foobar</div>
I tried several things to select these strings randomly, using range, shuffle, first 1, but I failed.
One popular error was:
error calling shuffle: can't iterate over map[string]interface {}
But I’ve got several other error messages.
I am sure that the solution is dead simple, Can someone give me a hint?
pamubay
2
shuffle
only supports array/slice. your colorschemes combinations are array of objects.
so we need to shuffle the index of each combination instead.
{{ $combinations := .Site.Data.colorschemes.combinations }}
{{ $random := int (delimit (first 1 (shuffle (seq 0 (sub (len $combinations) 1)))) "") }}
{{ $class := "" }}
{{ range $color, $bgColor := index $combinations $random }}
{{ $class = print $color " " $bgColor }}
{{ end }}
{{ $class }}
1 Like
You might want to add the code that is shuffleing. I think whats possible is this yaml type:
combinations:
-
- color: dark-red
bg-color: white
- color: black
bg-color: white
- color: gold
bgcolor: white
This way you can properly call $color and $bgcolor (at least in a range
command).