按Jekyll中的姓氏排序

  • 本文关键字:排序 Jekyll jekyll
  • 更新时间 :
  • 英文 :


我正在管理一个静态博客,里面有一大堆人名。我需要按姓氏的字母顺序给这些人排序。如果名字是一个字符串,如何按姓氏排序?例如:

{% assign People = "John Smith, Foo Bar, Zee Mack Arlington" | split: "," %}
<!-- How do I sort People by last name -->
{% assign sortedPeople = People | sort_natural %}
{% for person in sortedPeople %}
<p>{{ person }}</p>
{% endfor %}

这给了我一个按名字字母顺序排列的人的列表,但我需要按姓氏排序。

Foo Bar
Zee Mack Arlington
John Smith

Liquid在设计上有点限制,但有一种方法:

{% assign sorted_names = "" | split: "" %}
{% assign names_prefixed_with_last = "" | split: "" %}
{% assign names = "John Smith, Foo Bar, Zee Mack Arlington" | split: "," %}
{% for name in names %}
{% assign name_parts = name | split: " " %}
{% assign last_name = name_parts | last %}
{% assign name_prefixed_with_last = name | prepend: last_name %}
{% assign names_prefixed_with_last = names_prefixed_with_last | push: name_prefixed_with_last %}
{% endfor %}
{% assign sorted_with_prefix = names_prefixed_with_last | sort %}
{% for name_with_prefix in sorted_with_prefix %}
{% assign name_parts = name_with_prefix | split: " " %}
{% assign last_name = name_parts | last %}
{% assign name = name_with_prefix | replace_first: last_name %}
{% assign sorted_names = sorted_names | push: name %}
{% endfor %}
{% for name in sorted_names %}
<p>{{ name }}</p>
{% endfor %}

该输出:

<p>Zee Mack Arlington</p>
<p>Foo Bar</p>
<p>John Smith</p>

首先,我们使用拆分空字符串技巧创建几个数组,然后用以姓氏为前缀的名称填充数组(例如"SmithJohnSmith"(。然后我们对其进行排序,因为它将根据姓氏进行排序,然后用已排序的带前缀的数组的值填充数组,去掉前缀。


虽然我对问题范围没有任何其他知识,但更好的方法可能是用其他东西对它进行排序,并将它放在数据文件中。您也可以将它们存储在一个数组中,而不是一个庞大而笨拙的字符串中。

最新更新