Is there a way to get "really deterministic" randomness?

Dear community - please bear with me, I’m new here :slight_smile:

for my blog-in-preparation (nothing to show publically yet), I’m trying to show, near the top of all pages, a kind of “random quote”, which should be drawn from an array of quotes in a data file. Ideally I would really like to have the same quote for a given run of “hugo”…

What I have so far, is a partial with this content:

{{ with .Site.Data.kaffeespruch.wochen }}<h2 class="logo__tagline">{{ index (. | shuffle | first 1) 0 }}</h2>{{ end }}

which is then used, in a single other partial, like this:

{{ partialCached "base/logosub" . }}

While testing, I find that that works most of the time. Testing with two different quotes, it is okay two out of 50 tries or so. But sometimes, rarely. I get one or two pages out of 30 with a different quote than the others.

I also tried putting that partialCached call “one further up” the chain of partials I have - and in that case, found that the “nonstability” even happens more often.

I suspect there is some kind of parallelism involved, giving these rare results…

Now, my primary question here, would be: is there a better way to achieve my goal, which would also be really stable?

thanks for any hints


Yes, you are right – the locking in the cached partial means that the same partial can be called twice. It was built for speed and not for stability. We could fix that, I guess, if you could create a GitHub issue.

I cannot think of a current workaround. I thought about using Scratch – but that will have the same issue.

For a workaround, how about:

{{ with .Site.Data.kaffeespruch.wochen }}
  <h2 class=“logo__tagline”>{{ index . (mod (mod now.Unix 18000) (len .)) }}</h2>
{{ end }}

It breaks when your site build starts just before a five-minute boundary, but otherwise is consistent.


1 Like

Thanks for the confirmation of my guess. I don’t feel my use case is important enough to justify fixing the locking there - as long as other uses don’t run in important correctness issues. Hugo doesn’t have callout to external programs, write to files, or similar side effect stuff, right? Then it’s probably good as it is.

For my use case, I’ll try the other suggestion, using a modulo thing based on unix.time is totally okay for me.

Thanks jgreely! I don’t know why I didn’t think of that myself, I’m totally fond of unixtime modulo magic :slight_smile:

The formula has to be a bit different, using div on now.Unix - and your double quote characters were funny. Here’s what I have now, and it’s working perfectly for me:

{{ with .Site.Data.kaffeespruch.wochen }}
<h2 class="logo__tagline">{{ index . (mod (div now.Unix 300) (len .)) }}</h2>
{{ end }}

That’s what I get for making it up on the fly. :slight_smile:


1 Like

1 Like