Get Random Number Using Liquid

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.


Frank Lin

Hey, there! This is Frank Lin (@flinhong), one of the 1.4 billion 🇨🇳. This 'inDev. Journal' site holds the exploration of my quirky thoughts and random adventures through life. Hope you enjoy reading and perusing my posts.


Using Liquid in Jekyll - Live with Demos

Web Notes


Using Liquid in Jekyll - Live with Demos

Liquid is a simple templating language that Jekyll uses to process pages on your site. With Liquid you can output an modify variables, have logic statements inside your pages and loop over content.

Practising closures in JavaScript

JavaScript Notes


Practising closures in JavaScript

JavaScript is a very function-oriented language. As we know, functions are first class objects and can be easily assigned to variables, passed as arguments, returned from another function invocation, or stored into data structures. A function can access variable outside of it. But what happens when an outer variable changes? Does a function get the most recent value or the one that existed when the function was created? Also, what happens when a function invoked in another place - does it get access to the outer variables of the new place?

Syntax highlight with Rouge in Jekyll



Syntax highlight with Rouge in Jekyll

By default, Jekyll 3 and above versions integrated with Rouge, a pure Ruby syntax highlighter which supports over 100 languages. Since Rouge themes are compatible with Pygments’s stylesheets, it’s nice for us to choose a favourable style.