shopifyliquid

How to generate random number in liquid shopify?


If logic contains a date object please note that the value will be the current time of when the page was last generated from the template, not when the page is presented to a user if caching or static site generation is involved as per the Shopify article. It will return a similar number every time.


Solution

  • You can use the timestamp to get a large number and use math to get a random-looking result. Eg to get a random number between 0 and 100:

    {% assign randomNumber = "now" | date: "%N" | modulo: 100 %}
    

    (remember that this will generate an integer anywhere from 0 to 99 inclusive.)

    Or a random number between 10 and 20:

    {% assign min = 10 %}
    {% assign max = 20 %}
    {% assign diff = max | minus: min %}
    {% assign randomNumber = "now" | date: "%N" | modulo: diff | plus: min %}
    

    NB: Liquid files are cached so the random number is only generated on page creation and doesn't change every time you view the page. For that, you would need javascript.