Jeykll:按公共属性对 _data 子文件夹中的文件进行排序

lig*_*ght 5 sorting for-loop liquid jekyll

我想迭代 中的每个文件_data/sections/,但输出按所述文件中包含的数据(顺序属性)排序。当前的输出恰好是正确的顺序,尽管我不确定为什么,并且修改排序属性时顺序不会改变

文件的结构如下:

// project/_data/sections/food.yml

title: Food
order: 2
content: "Food ipsum dolor sit amet."

-----

// project/_data/sections/drink.yml

title: Drink
order: 1
content: "Drink ipsum dolor sit amet."
Run Code Online (Sandbox Code Playgroud)

按照Jekyll 文档中数据文件的结构,for 循环代码如下:

// project/index.html

// ...
{% for section_hash in site.data.sections | sort: 'order' %}
  {% assign section = section_hash[1] %}
  <p><strong>{{ section.title }}</strong> - {{ section.content }}</p>
{% endfor %}
// ...
Run Code Online (Sandbox Code Playgroud)

我还尝试在将这些部分传递到 for 循环之前对其进行排序,如下所示

{% assign sections_sorted = sita.data.sections | sort: 'order' %}
{% for section in sections_sorted %}
  <p><strong>{{ section.title }}</strong> - {{ section.content }}</p>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

最后,我尝试将该order属性移动到 中每个节文件的前面_data/sections/,但这导致了异常:Liquid Exception: no implicit conversion of String into Integer

// project/_data/sections/drink.yml
---
order: 1
---

title: Drink
content: "Drink ipsum dolor sit amet."
Run Code Online (Sandbox Code Playgroud)

的子目录中的文件可以这样做吗_data/?如何按数字顺序order、按字母顺序反向title等等对这些文件的输出进行排序?

小智 0

我不确定我的问题是否与你的有关。我正在尝试对_data目录中的文件进行排序,但我的文件是 JSON 格式。无论我做什么,我都会收到此错误消息:jekyll 2.5.3 | Error: no implicit conversion of String into Integer。我的 JSON 文件根本不包含任何 frontmatter。错误消息告诉我,Ruby 尝试使用字符串访问数组,但出于某种原因需要整数,例如my_array["blah"]而不是my_array[1]。这没有多大意义,因为sort:"blah"实际上提供了一个字符串。您能解决这个问题吗?

关于你的第一个例子:
{% for section_hash in site.data.sections | sort: 'order' %}
我认为这不起作用,我相信这没有在 Liquid 中实现。请参阅此问题: https: //github.com/Shopify/liquid/pull/304

但我不明白为什么你的第二个例子不起作用,也许我在这里误解了一些东西:显然
{% assign sections_sorted = sita.data.sections | sort: 'order' %}
,这应该从 Jekyll 2.2.0 开始工作,请参阅这个线程:Sorted navigation menu with Jekyll and Liquid