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 -%}
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" -%}
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 -%}
Finally, add your min
value to the result.
{%- assign random_number = random_number | plus: min -%}
In short:
{%- assign min = 0 -%}
{%- assign max = 9 -%}
{%- assign diff = max | minus: min -%}
{%- assign random_number = "now" | date: "%N" | modulo: diff | plus: min -%}
You can use it as snippets as well:
{% render 'random-number' %} # snippets with random number code
{{ random_number }} # here's your random number
Β
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)