Specifically I'm looking to list an array's contents in random order on a page each time it is generated.
So, given page.array = [1, 2, 3]
the following:
{% for i in page.array %}
<p>{{ i }}</p>
{% endfor %}
<!--
Yields:
<p>1</p>
<p>2</p>
<p>3</p>
-->
How do I randomize that order? (hopefully with syntax somewhat like the following)
{% for i in page.array.shuffle %}
<p>{{ i }}</p>
{% endfor %}
<!--
Yielding something like this, or a random reordering:
<p>3</p>
<p>1</p>
<p>2</p>
-->
I managed to achieve this by adding a custom filter via Jekyll's plugin system:
# _plugins/shuffle.rb
module Jekyll
module ShuffleFilter
def shuffle(array)
array.shuffle
end
end
end
Liquid::Template.register_filter(Jekyll::ShuffleFilter)
And using:
{% assign shuffled_array = page.array | shuffle %}
{% for i in shuffled_array %}
<p>{{ i }}</p>
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With