Liquid:我可以从数组中获取随机元素吗?

发布于 2025-01-03 18:16:34 字数 214 浏览 4 评论 0原文

我正在尝试从数组中选择一个随机元素——使用 Liquid/Jekyll 可以吗?

我可以创建一个数组 - 并访问给定的索引...但是有没有办法“洗牌”数组,然后选择一个索引,从而从数组中获取随机元素?

prefix: ["Foo", "Bar", "Baz"]
---

{{ page.prefix[1] }}

# outputs "Bar"

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"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

热鲨 2025-01-10 18:16:34

2018 年的答案是

{% assign prefix = page.prefix | sample: 2 %}
{{ prefix[0] }}

这是一个 Jekyll 特定的过滤器,记录在 https://jekyllrb。 com/docs/liquid/filters/#sample

The 2018 answer is

{% assign prefix = page.prefix | sample: 2 %}
{{ prefix[0] }}

This is a Jekyll-specific filter which is documented at https://jekyllrb.com/docs/liquid/filters/#sample

若能看破又如何 2025-01-10 18:16:34

Liquid 没有用于从数组或整数区间中选取随机元素的过滤器。

如果您希望 Jekyll 这样做,您必须创建一个扩展来添加该液体过滤器。

但是,我必须指出,这样做会在每次生成页面时选择一个随机元素,但不是每次查看页面时都会选择一个随机元素。

如果您想在每次访问页面时获得不同的随机值,最好的选择是使用 javascript 并让客户端选择一个随机值。不过,您可以使用 Liquid 来生成相关的 javascript。

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.

习惯成性 2025-01-10 18:16:34

您也许可以在 Liquid 中做到这一点,但它可能不像@Brendan 提供的那样通用解决方案。根据这篇文章,您可以生成一个介于 min 和 to 之间的随机液体数。最大限度。很简单:

  • 将最小值指定为 0,将最大值指定为数组的长度。
  • 循环数组,直到找到随机数并选择元素。

这是一个例子,获取你的随机数组索引:

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

然后找到你的随机值:

{{ prefix[randomNumber] }}

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] }}
山田美奈子 2025-01-10 18:16:34

您可以创建一个插件来获取随机元素。像这样的事情:

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)

然后在模板中执行类似的事情来实现:

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

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 %}
脱离于你 2025-01-10 18:16:34

不使用插件(例如,如果您使用 github 页面,这可能是一个要求)并且不希望仅在构建/重建时设置该选择。

它使用集合作为数据源,并在页面前面设置一些功能标志。

{% if page.announcements %}
    <script>
        // homepage callout
        var taglines=[ 
         {% for txt in site.announcements %} 
           {{ txt.content | markdownify | jsonify | append: "," }}
        {% endfor %}
        ]
        var selection = document.querySelector('#tagline') !== null;
        if(selection) {
            document.querySelector('#tagline').innerHTML = taglines[ Math.floor(Math.random()*taglines.length) ];
        }
     </script>
{% endif %}

我使用 markdownify 来处理内容,使用 jsonify 来使其 JavaScript 安全,然后附加一个逗号来创建我的数组。

然后 JavaScript 在页面加载时随机填充一个。

向 config.yml 添加集合

collections:
   announcements:

向页面添加标志

---
layout: home
title: 
slider: true
announcements: true    
---

集合内容项 (test.md)

---    
published: true
---

This is a test post

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.

{% if page.announcements %}
    <script>
        // homepage callout
        var taglines=[ 
         {% for txt in site.announcements %} 
           {{ txt.content | markdownify | jsonify | append: "," }}
        {% endfor %}
        ]
        var selection = document.querySelector('#tagline') !== null;
        if(selection) {
            document.querySelector('#tagline').innerHTML = taglines[ Math.floor(Math.random()*taglines.length) ];
        }
     </script>
{% endif %}

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

collections:
   announcements:

Add flag to page

---
layout: home
title: 
slider: true
announcements: true    
---

collection content item (test.md)

---    
published: true
---

This is a test post
傾旎 2025-01-10 18:16:34

您可以调整 Liquid::Drop 和白名单 Ruby 的示例方法

请参阅https://github.com/Shopify/liquid/ blob/master/lib/liquid/drop.rb#L69

您需要将:更改

blacklist -= [:sort, :count, :first, :min, :max, :include?]

为:

blacklist -= [:sort, :count, :first, :min, :max, :include?, :sample]

接下来您可以使用:

{{ some_liquid_array.sample }}   

You could adapt Liquid::Drop and whitelist Ruby's sample method.

See https://github.com/Shopify/liquid/blob/master/lib/liquid/drop.rb#L69:

You would need to change:

blacklist -= [:sort, :count, :first, :min, :max, :include?]

to:

blacklist -= [:sort, :count, :first, :min, :max, :include?, :sample]

Next you could just use:

{{ some_liquid_array.sample }}   
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文