Liquid: Can I get a random element from an Array

jekyllliquid

I'm trying to pick a random element from an array — is this possible using Liquid/Jekyll?

I can create an array — and access a given index … but is there a way to "shuffle" the array and then select an index, and thus get a random element from the array?

prefix: ["Foo", "Bar", "Baz"]
---

{{ page.prefix[1] }}

# outputs "Bar"

Best Answer

The 2018 answer is

{% assign prefix = page.prefix | sample: 2 %}
{{ prefix[0] }}

As the OP asked about Jekyll, this can be found at: https://jekyllrb.com/docs/templates/

Related Topic