Get Random Number Using Liquid

Generate random numbers in Liquid was once possible with built-in rand(), but it has been taken out because it’s easy to replicate in JavaScript and doesn’t benefits to server side caching. However, you can actually get a random number in Liquid through a simple trick: making use of both the date & modulo Liquid filters1.

For example in a Jekyll project, get a random number like follows:

  1. Get the current date, using site.time;
  2. Extract the nanoseconds value from the date, using %s date filter;
  3. Use the module filter to get the random number between the min & max settings;
  4. Eventually, add the min value to the result.

And here is an example, generate a random number between 50 to 100:

{% assign min = 50 %}
{% assign max = 100 %}
{% assign diff = max | minus: min %}
{% assign randomNumber = site.time | date: "%s" | modulo: diff | plus: min %}

However, the randomNumber is actually fixed because the site.time is fixed once you start building the static files. It’s only random among different builds. You can, just replace the site.time with anything that can be converted into intergers. So, I’ve decided to use the page.content | size to replace the site.time at present for a pseudo random number.

Did you know that you can generate numbers in SCSS?

The random(param:max) is available in SCSS.