DEV Community

Cover image for How to generate a random number in Shopify?
Pierre Grimaud
Pierre Grimaud

Posted on

How to generate a random number in Shopify?

Hello there, this is my first post in DEV. 🙋🏻‍♂️

__

Random is always useful, even on e-commerce environments. Showing random products or pictures for example, could be nice.

What's the problem?

Liquid is a template language created by Shopify and written in Ruby. It is the backbone of Shopify themes and is used to load dynamic content on storefronts.

There's an awesome Shopify cheat sheet with basics, tags, filters and objects available on Liquid. But the are no tags to pick a random number from a range or just generate one.

Let me explain you how to do it with a simple trick.

How?

First, define min and max numbers. They will be use as range to generate a random number.

{%- assign min = O -%}
{%- assign max = 9 -%}
Enter fullscreen mode Exit fullscreen mode

Then, get the current date with "now" and apply the "%N" date filter to get fractional seconds digits (precise to nanoseconds).

{%- assign date_fract = "now" | date: "%N" -%}
Enter fullscreen mode Exit fullscreen mode

Next, use the modulo filter to get a random value between your min & max values.

{%- assign diff = max | minus: min -%}
{%- assign random_number = "now" | date: "%N" | modulo: diff -%}
Enter fullscreen mode Exit fullscreen mode

Finally, add your min value to the result.

{%- assign random_number = random_number | plus: min -%}
Enter fullscreen mode Exit fullscreen mode

In short:

{%- assign min = 0 -%}
{%- assign max = 9 -%}
{%- assign diff = max | minus: min -%}
{%- assign random_number = "now" | date: "%N" | modulo: diff | plus: min -%}
Enter fullscreen mode Exit fullscreen mode

You can use it as snippets as well:

{% render 'random-number' %} # snippets with random number code 
{{ random_number }} # here's your random number
Enter fullscreen mode Exit fullscreen mode

 
With a random number, you can now pick a random value in an array of products, pictures or whatever. 💯

Limitations

On Shopify, store pages are aggressively cached. Using it on production theme may not work as intended and random numbers could be stuck for minutes or hours.

Adding a product to card or editing a product on Shopify back-end will flush cache, so use is wisely.

Wanna more?

This code comes from a repository Shopify snippets with "ready to use" parts of code which can be reusable when developing Shopify themes.

Put a 🌟 if this post helped you. :)

 
Pierre 🤖
 
__
Follow me on GitHub
Follow me on Twitter
 
Cover image via Pixabay

Top comments (0)