Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jekyll

liquid

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"
like image 686
rsturim Avatar asked Feb 08 '12 10:02

rsturim


2 Answers

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/

like image 113
Merovex Avatar answered Sep 18 '22 20:09

Merovex


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.

like image 45
kikito Avatar answered Sep 19 '22 20:09

kikito