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>
首先,我们使用拆分空字符串技巧创建几个数组,然后用姓氏前缀的名称填充一个数组(例如“SmithJohn Smith”)。然后我们对其进行排序,因为它将按姓氏排序,然后使用已排序的前缀数组的值填充一个数组,其中删除了前缀。
尽管我对问题范围没有任何其他了解,但更好的方法可能是用其他东西对其进行排序并将其放入数据文件中。您也可以将它们存储在一个数组中,而不是一个巨大的笨拙的字符串。
推荐阅读
- mysql - 锁定表会导致 django 的保存点问题
- javascript - 在解决原始承诺之前等待嵌套的 JS 承诺完成
- .net - 无法加载文件或程序集“System.IO.Pipelines”
- wordpress - WP主页上的无限循环
- mongodb - 地址访问无效:Mongo v4.0.5 为 0
- excel - 是什么导致 VBA 用户窗体中的 -2147352571 类型不匹配错误?
- javascript - Angular Material mat-select 设置默认选择值
- wordpress - 一个产品有多个实例,每个实例销售一次
- c# - Azure 存储客户端加密
- visual-studio-2013 - 如何更改 Abaqus 求解器可执行文件名