Liquid: Can I get a random element from an Array?

rsturim picture rsturim · Feb 8, 2012 · Viewed 8.4k times · Source

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"

Answer

kikito picture kikito · Feb 8, 2012

Liquid doesn't have a filter for picking a random element from an array or an integer interval.

If you want Jekyll to do that, you would have to create an extension to add that liquid filter.

However, I must point out that doing so would pick a random element every time the page is generated, but not every time the page is viewed.

If you want to get different random values every time you visit a page, your best option is using javascript and letting the client pick a random value. You can use liquid to generate the relevant javascript though.