首页 > 解决方案 > 在 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

标签: jekyll

解决方案


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>

首先,我们使用拆分空字符串技巧创建几个数组,然后用姓氏前缀的名称填充一个数组(例如“SmithJohn Smith”)。然后我们对其进行排序,因为它将按姓氏排序,然后使用已排序的前缀数组的值填充一个数组,其中删除了前缀。


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


推荐阅读