如何在Liquid中对转换为数组的哈希进行排序

Dan*_*ell 11 liquid jekyll

我的理解是Liquid将Ruby Hashes转换为数组以用于标记.例如,使用Jekyll时:

{% for category in site.categories %}
    <li>{{ category[0] }}</li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

...将site.categories转换为元组数组,其中[0]表示键,[1]表示值.

如果我想通过键(每个元组的[0])按字母顺序对上面的类别映射进行排序,我该怎么办?

小智 9

这是一个老问题,但我只花了最后一点时间为自己搞清楚这一点.我使用以下代码来实现您(和我)想要的.

{% capture get_items %}
 {% for cat in site.categories %}
   {{ cat | first }}
 {% endfor %}
{% endcapture %}
{% capture num_words %}
 {{ get_items | split:' ' |  sort | join:' ' | number_of_words }}
{% endcapture %}
{% for item in (1..num_words) %}
 <li>{{ get_items | split:' ' |  sort | join:' ' | truncatewords:item | remove:'.    ..' |    split:' ' | last }}</li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ris 7

您也可以使用数组而不是哈希!

而不是使用这个yaml:

categories:
  a_category: category description
  another_category: another category description
Run Code Online (Sandbox Code Playgroud)

你可以用这个:

categories:
  - {name: 'a category', description: 'category description'}
  - {name: 'another category', description: 'another category description'}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样迭代,订单将被保留:)

{% for category in site.categories %}
  <li>{{ category['name'] }}</li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)


kik*_*ito 1

默认的 Liquid 实现和 Jekyll 所做的添加都无法满足您的需求。

恐怕当前的设置根本无法实现您想要的。您必须对 Jekyll 或 Liquid 进行 Monkeypatch 才能使散列按排序顺序返回它们的键。