Hugo How to generate random numbers

Goal

In a previous post I have created a partial template to generate some html code to display images using . Now I would like to generate a random number to use to rotate the image to give it a more realistic look. (Like those polaroids you throw on a table).

Getting a Seed to generate a random number

To create a seed, simply create a new variable to get the current timestamp using {{ $seed := now.UnixNano }}. now.UnixNano will generate a very long timestamp going down to the nano second. But there is no way to use a random function like in other languages, so we need some trick.

Random number expectations

I want to use the “random” generated number to rotate on the left or on the right my picture. The amplitude should be around 10 degrees. I choose an odd number so that the middle value would be my 0. The modulo function will get me a number between 0 to 22 then I will substract 11 from that number to get a negative or a positive rotation. When I get 0 I will rotate the image of -11 degrees, when I get 22 the rotation will be of 11 degrees. That fit perfectly my needs.

{{ sub ( mod ( $seed  22 ) 11 }}

Because the operation was so fast, I would get the same result for all the pictures. I tried using some mathematic functions to slow down the operation but I was unlucky. This is also the reason why I used now.UnixNano instead of now.Unix. No luck. As I had 2 parameters in the partial, I decided to multiply their lengths and divide the seed by that value. In most of the cases, I should have completely different numbers.

{{ sub ( mod ( div $seed  (mul ( len .img ) ( len .title) )) 22 ) 11 }}

And now I have my random number.

Now I need to generate another number to set the Z axis, between 0 and 90.

1
2
3
4
5
6
7
{{ $seed := now.UnixNano  }}
<div style="transform:rotate( {{ sub ( mod ( div $seed  (mul ( len .img ) ( len .title) )) 22 ) 11 }}deg);z-index:{{ mod ( div $seed  (mul ( len .img ) ( len .title) )) 90 }};" >
    <figure class="snap">
        <img  src="{{ .img }}" alt="{{ .title }}"  />
        <figcaption>{{ .title }} </figcaption> 
    </figure>
</div>

Result

Random Number Generation Result

References