Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I shuffle the order of an array in Jekyll?

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>
-->
like image 212
Mike Jarema Avatar asked Dec 09 '22 05:12

Mike Jarema


1 Answers

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 %}
like image 144
Mike Jarema Avatar answered Dec 30 '22 23:12

Mike Jarema