Last active
August 12, 2024 18:00
-
-
Save callaginn/a4225da5d3aeb5db7b8ba079f4049fc3 to your computer and use it in GitHub Desktop.
Shopify Liquid Randomly Shuffle Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{%- comment -%} | |
Randomly Shuffle Liquid Array | |
Author: Stephen Ginn at cremadesignstudio.com | |
Credits: Random Number function from @131_studio | |
Usage: {%- include 'random' with 'a,b,c,d,e' -%} | |
This snippet does the following: | |
1. Creates a new array with the provided string | |
2. Calculate X amount to loop, based on array size times 10. | |
3. Loop X number to generate random indexes using fancy date and math logic. | |
4. Strip out duplicate keys and echo new array. That's why we looped 10x the array size. | |
{%- endcomment -%} | |
{%- assign array = random | split: ',' -%} | |
{%- assign loops = array.size | times: 10 -%} | |
{%- capture indexes -%} | |
{%- for i in (1..loops) -%}{{ "now" | date: "%N" | modulo: array.size }},{%- endfor -%} | |
{%- endcapture -%} | |
{%- assign indexes = indexes | split: ',' | uniq -%} | |
{%- for a in indexes -%}{% assign b = a | plus: 0 %}{{ array[b] }}{% unless forloop.last %},{% endunless %}{%- endfor -%} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Appears to not really be random. It's random as of the build time & then it's cached. SCSS & JavaScript remain the easier ways to randomize.