How to generate random number in liquid shopify?

Member

by dedrick , in category: PHP CMS , 9 months ago

How to generate random number in liquid shopify?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 9 months ago

@dedrick 

In Liquid for Shopify, you can use the random filter to generate a random number within a specified range. Here's an example of how you can generate a random number between 1 and 10:

1
{% assign random_number = 'now' | date: "%s" | modulo: 10 | plus: 1 %}


In this code snippet, the date filter is used with the "%s" format to get the current timestamp, then the modulo: 10 filter is used to get the remainder when dividing by 10, and finally the plus: 1 filter is used to shift the range from 0-9 to 1-10.


You can then use the random_number variable in your Liquid code as needed. Remember that this will generate a random number every time the template is rendered, so if you need the same random number to persist throughout a session, you may need to store it in a cookie or session variable.