My WebSite uses a Json data file. To select a random element of this dataset, i want to select all keys of this dictionary.
I scanned the documentation but found no hint on how to perform this operation (probably with apply).
Accessing the records by their keywords is no problem…
{{ $title := .Title }}
{{ $baseUrl := .Site.BaseURL }}
{{ with .Site.Data.cover.uhd }}
<section id="cover-report" style="background: #222 url('{{ $baseUrl }}/img/fullscreen/{{ .img }}') no-repeat center top;">
<div id="cover-caption">
<div class="container">
<div class="col-sm-10 offset-sm-1">
<h1>{{ $title }}</h1>
{{ if .caption }}
<p>{{ .caption }}</p>
{{ end }}
</div>
</div>
{{ if .credits }}
<div class="credits">{{ .credits }}{{ if .url }} (<a class="external" href="http://{{ .url }}">{{ .url }}</a>){{ end }}</div>
{{ end }}
</div>
</section>
{{ end }}
(This partial is still incomplete.)
I’d like to select a random cover-image in case the page did not ask for a specific background. Therefore I’d expected to select it something like this:
{{ $randomCoverKey := SOME_KEY_EXTRACTING_FUNCTION .Site.data.cover | shuffle | first 1 }}
{{ with index .Site.date.cover $randomCoverKey }}
As for the random element, you could put the keys into a list and select one at a random index, then use that to select the corresponding element. So something like:
{{ $keys := slice }}<!-- hold all the keys in an array -->
{{ $cov := .Site.Data.cover }}<!-- for brevity -->
{{ range $key, $val := $cov }}
<!-- append each key to list of keys -->
{{ $keys = $keys | append $key }}
{{ end }}
<!-- use seq to generate a series from 0 to len-1, then shuffle, then get the first number -->
{{ $rand := index (shuffle (seq 0 (sub (len $keys) 1)) ) 0 }}
<!-- $cov[$keys[$rand]] -->
{{ $randomelement := index $cov (index $keys $rand) }}
The actual code is slightly more complicated because the post might decide to define the cover image that should be visible on the top of the page. But for all pages that are indecisive this made my day.
While still under massive change you might have look at my first Hugo-made website: