简体   繁体   English

如何在 Jekyll 中打乱数组的顺序?

[英]How do I shuffle the order of an array in Jekyll?

Specifically I'm looking to list an array's contents in random order on a page each time it is generated.具体来说,我希望每次生成时在页面上以随机顺序列出数组的内容。

So, given page.array = [1, 2, 3] the following:因此,给定page.array = [1, 2, 3]以下内容:

{% for i in page.array %}
  <p>{{ i }}</p>
{% endfor %}

<!-- 
  Yields:
  <p>1</p>
  <p>2</p>
  <p>3</p>
-->

How do I randomize that order?我如何随机化该顺序? (hopefully with syntax somewhat like the following) (希望语法有点像以下)

{% for i in page.array.shuffle %}
  <p>{{ i }}</p>
{% endfor %}

<!--
  Yielding something like this, or a random reordering:
  <p>3</p>
  <p>1</p>
  <p>2</p>
-->

I managed to achieve this by adding a custom filter via Jekyll's plugin system:我设法通过 Jekyll 的插件系统添加自定义过滤器来实现这一点:

# _plugins/shuffle.rb
module Jekyll
  module ShuffleFilter
    def shuffle(array)
      array.shuffle
    end
  end
end

Liquid::Template.register_filter(Jekyll::ShuffleFilter)

And using:并使用:

{% assign shuffled_array = page.array | shuffle %}
{% for i in shuffled_array %}
  <p>{{ i }}</p>
{% endfor %}

The currently accepted answer uses a custom filter, but this is not possible in some common Jekyll environments, such as GitHub Pages.当前接受的答案使用自定义过滤器,但这在一些常见的 Jekyll 环境中是不可能的,例如 GitHub Pages。

An easy workaround that does work on GitHub Pages is to use Jekyll's sample filter and pass it the size of the array.在 GitHub Pages可行的一个简单解决方法是使用Jekyll 的sample过滤器并将数组的size传递给它。 For example, here is a Markdown-formatted Jekyll template that will print the titles of your Jekyll blog posts in random order on each Jekyll build:例如,这是一个 Markdown 格式的 Jekyll 模板,它将在每个 Jekyll 构建中以随机顺序打印您的 Jekyll 博客文章的标题:

---
title: Posts in random order
---

{% assign n = site.posts | size %}
{% assign posts = site.posts | sample: n %}
{% for post in posts %}
    * {{ post.title }}
{% endfor %}

After trying solutions discussed here, I realized it is better using JS because I can shuffle the list dynamically anytime I want.在尝试了这里讨论的解决方案后,我意识到使用 JS 更好,因为我可以随时动态地调整列表。 It is easy to implement.这很容易实现。 Here is an example:下面是一个例子:

html html

<div id="my-list">
  {% for i in page.array %}
    <p>{{ i }}</p>
  {% endfor %}
</div>

js js

var myList = document.querySelector('#my-list');
for (var i = myList.children.length; i >= 0; i--) {
    myList.appendChild(myList.children[Math.random() * i | 0]);
}

Reference: javascript - shuffle HTML list element order参考: javascript - shuffle HTML 列表元素顺序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM