How To: Use random numbers to show random background images in your templates

A few of our amazing clients have asked for a way to do some random stuff with their templates, like showing a random background image in their layouts. This and many other examples can be accomplished by using the random function we’ve added to our template language. Let me explain how it works:

The random() function can be used in your templates to generate a random number between any two numbers, like so:

{{ random(1,10) }} //prints any random number between 1 and 10
{{ random(2,5) }} //prints 2, 3, 4 or 5

If we use this together with an array, we can easily build the example that was requested by one of our clients to show a random background image to its users.

First we create a small array with any number of background images we want to shuffle:

{% set wallpapers = ["image1.jpg", "image2.jpg", "image3.jpg"] %}

As you might know, arrays always start counting from zero, so element 0 is “image1.jpg”, element 1 is “image2.jpg” and so on. So if we take this one step further, we need to be able to get one of those elements randomly, by picking any element 0, 1 or 2 from the array.

{% set whichwallpaper = random(0,2) %}

That will give us either 0, 1 or 2. Now that we’ve got our random number, all that’s left is grab the correct image from the array and show it as a background image in our templates.

{{ wallpapers[whichwallpaper] }}

That will print out “image1.jpg”, “image2.jpg” or “image3.jpg” depending on the random number that was generated. Putting it all together, we can now show a random background image to our users like so:

{% set wallpapers = ["image1.jpg", "image2.jpg", "image3.jpg"] %}
{% set whichwallpaper = random(0,2) %}
<body style="background-image: url('{{ wallpapers[whichwallpaper] }}')">

Et voila, there you have it folks. Make sure to post any questions or remarks in the comments below.