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

后端 未结 6 950
甜味超标
甜味超标 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:33

    You can create a plugin to get a random element. Something like this:

    module Jekyll
      module RandomFilter
        # Use sample to get a random value from an array
        #
        # input - The Array to sample.
        #
        # Examples
        #
        #   random([1, 2, 3, 4, 5])
        #   # => ([2])
        #
        # Returns a randomly-selected item out of an array.
        def random(input)
          input.sample(1)
        end
      end
    end
    
    Liquid::Template.register_filter(Jekyll::RandomFilter)
    

    Then do something like this in your template to implement:

    {% assign myArray = '1|2|3|4|5 | split: '|' %}
    {% assign myNumber = myArray | random %}
    

提交回复
热议问题