So this is a rather silly idea I’ve been wanting to try.
I have a heading and I want to randomly offset the y-position of every individual character. Probably by wrapping it in a with a style attribute. Could I do that with the template language?
There is no rand() function in Hugo. It would probably be pretty easy to add one, and I guess there are other situations where it could be useful, so it may be worth requesting…
To get around that, you could put a bunch of numbers in an array, then use the shuffle function, then index to generate a random number… something like
{{ index (shuffle (seq 0 9)) 0 }}
If you need to roll it into a loop so you can use a string supplied by the user, something like this should work:
{{ range $i := seq 0 (sub ($.Title | len) 1) }}<span style="margin-left: {{ index (shuffle (seq 0 9)) 0}}">{{ slicestr $.Title $i (add $i 1) }}</span>{{ end }}
Note that you’ll probably want everything on one line to avoid introducing whitespace on accident.
That said, you might want to consider doing this in JavaScript so it gets randomized every time a page loads instead of just when it is generated.
Thanks, will definitely give this approach a shot
It’s working
Here’s the code I used:
{{ $mult := 8 }}
{{ $lower := 1 }}
{{ $len := (sub (len .Title) 1) }}
{{ $randArr := (shuffle (seq $lower (add $lower $len))) }}
{{ range $i := (seq 0 (sub (len .Title) 1)) }}
{{ $offset := (div (mul (index $randArr $i) $mult) $len) }}
<span style="display: inline-block; transform: translate(0px, {{ $offset -}} px);">
{{ slicestr $.Title $i (add $i 1) }}
</span>
{{ end }}