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"
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.
Without using a plugin (which might be a requirement if you are using github pages for example) and don't want the choice to be set only at build/rebuild time.
This uses collections as it's data source and some feature flags set in the page front matter.
I use markdownify to process the content, jsonify to make it JavaScript safe and then append a comma to make my array.
The Javascript then populates one randomly at page load.
Add collection to config.yml
Add flag to page
collection content item (test.md)
You could adapt
Liquid::Drop
and whitelist Ruby'ssample
method.See https://github.com/Shopify/liquid/blob/master/lib/liquid/drop.rb#L69:
You would need to change:
to:
Next you could just use:
You may be able to do that just in Liquid, but it could less of generic solution like the one provided by @Brendan. According to this article, you can generate a random liquid number between min & max. So simply:
Here is an example, get your random array index:
Then find your random value:
The 2018 answer is
As the OP asked about Jekyll, this can be found at: https://jekyllrb.com/docs/templates/
You can create a plugin to get a random element. Something like this:
Then do something like this in your template to implement: