如何在 Liquid 中对转换为数组的哈希进行排序
我的理解是 Liquid 将 Ruby 哈希转换为数组以在标签中使用。例如,当使用 Jekyll:
{% for category in site.categories %}
<li>{{ category[0] }}</li>
{% endfor %}
... 将 site.categories 转换为元组数组,其中 [0] 指的是键,[1] 指的是值列表。
如果我希望上面的类别映射按键(每个元组的 [0])按字母顺序排序,我该怎么做?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这是一个老问题,但我只是花了最后一点时间来为自己解决这个问题。我使用以下代码来实现您(和我)想要的。
This is an old question, but I just spend the last little while figuring this out for myself. I used the following code to achieve what you ( and I ) wanted.
您还可以使用数组代替哈希!
而不是使用这个 yaml:
你可以使用这个:
然后你可以像这样迭代,并且顺序将被保留:)
You can also use arrays instead of hashes!
Instead of using this yaml:
You can use this one:
And then you can iterate like this, and order will be preserved :)
按字母顺序排序的标签的帖子索引(标签名称中不允许有空格):
Index of posts by alphabetically sorted tags (spaces not allowed in tag names):
您可以使用以下方法按键排序(与 Github Pages 兼容):
希望这会有所帮助。
You can sort by the key using the following method (that is compatible with Github Pages):
Hope this helps.
您可以为自己省去一些麻烦,扩展
Liquid
:例如
用法:
示例:
如果您觉得幸运,您可以在 github 上查找
for.rb
文件并扩展for
语法可以更好地处理哈希值:)。You could save yourself some trouble and extend
Liquid
:e.g.
Usage:
Examples:
If you feel lucky you can look on github for the
for.rb
file and extend thefor
syntax to handle hashes better :).默认的 Liquid 实现和 Jekyll 所做的添加都无法满足您的需求。
恐怕当前的设置根本无法实现您想要的。您必须对 Jekyll 或 Liquid 进行 Monkeypatch 才能使散列按排序顺序返回它们的键。
Neither the default Liquid implementation nor the additions made by Jekyll allow for what you want.
I'm afraid what you want is simply not possible with the current setup. You would have to monkeypatch Jekyll or Liquid in order to make the hashes return their keys in a sorted order.
我也想参加这个令人困惑的竞赛(伙计们,
number_of_words
,认真的吗?)。此代码逐个标记构建列表标记,在每一步中按字典顺序查找列表中的下一个标记。它的时间复杂度为 O(n²),其中 n 是标签数量。
顺便说一句,Liquid 的评论看起来沉重得荒谬。
I also want to be part of this obfuscated competition (dudes,
number_of_words
, seriously?).This code is building the list tag by tag, looking for the next tag in lexicographic order in the list at each step. It's in O(n²) where n is the number of tags.
BTW, Liquid comments look absurdly heavy.
以下是我解决 Nikos 问题的方法:
现在如何让它与 HAML 一起工作......
Here's how I fixed Nikos problem:
Now how to get this working with HAML...