Generate Random Number From 1 to 3 in Template

Can anyone help me. How do I generate random number from 1 to 3 in template?

I have this YouTube thumbnail image. Given below:

<img src="http://img.youtube.com/vi/Z6zdfAuzw-c/1.jpg">

I will later put it in my template so that it will generate video thumbnail automatically. It will get the video ID from article params and will choose random number from 1 to three.

<img src="http://img.youtube.com/vi/{{ .Params.videoid }}/{{ randomonetothree }}.jpg">

How do I do it to get the random number in {{ randomonetothree }} ?

Sometime the thumbnail generate by YouTube is different. That’s why I want to get them randomly.

I hope I describe it clear enough.

If you have better suggest on how to get the random thumbnail. I am happy to hear about it too.

Thank you.

There is no built-in random func in Hugo. This could be done in roundabout-way with the current time. There is examples of this somewhere on this forum.

In Hugo 0-16-DEV (latest source) you can do something like:

{{ seq 3 | shuffle | first 1 }}
2 Likes

Thanks for the information.

I guest, it’s either I have to find other solution or build Dev Hugo for my machine.

Right now I am using v0.15.

Thanks again.

Just tested it, this works:

{{ index (seq 3 | shuffle) 0 }}
2 Likes

I just tried this in my current template and it not working in my V0.15

<img src="http://img.youtube.com/vi/Z6zdfAuzw-c/{{ index (seq 3 | shuffle) 0 }}.jpg">

I’ll tried to build Dev Hugo first.

@bep Thanks.

I mange to install Dev Hugo v0.16.

Your code works as what I want.

Thanks again. :slight_smile: