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

后端 未结 6 929
甜味超标
甜味超标 2021-02-13 10:49

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 \

6条回答
  •  不知归路
    2021-02-13 11:07

    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:

    • Assign the min to 0 and max to your array's length.
    • Loop over the array till you find your random number and pick you element.

    Here is an example, get your random array index:

    {% assign min = 0 %}
    {% assign max = prefix.size %}
    {% assign diff = max | minus: min %}
    {% assign randomNumber = "now" | date: "%N" | modulo: diff | plus: min %}
    

    Then find your random value:

    {{ prefix[randomNumber] }}
    

提交回复
热议问题