Jekyll `_data/people.json` 数组:重组和排序

Jekyll `_data/people.json` arrays: reforming and sorting

我正在开发一个 Jekyll 项目,该项目在 _data 文件夹中有一个名为 people.json 的文件。 JSON 文件的格式如下:

{
    "name" : "George Michael",
    "topics" : ["Egg", "Cousins"],
    "contact" : [
        {
            "email" : "name@web.com",
            "twitter" : "@name"
        }
    ]
},
{
    "name" : "Tobias",
    "topics" : ["Analyst", "Therapist"],
    "contact" : [
        {
            "email" : "name@web.com",
            "twitter" : "@name"
        }
    ]
}

我想做的是使用 topics 信息建立一个标签列表,某种程度上。我试过:

{% for tag in site.data.people %}
<li>
    {{ tag.topics }}
</li>
{% endfor %}

哪个returns:

<li>EggCousins</li>
<li>AnalystTherapist</li>

理想情况下,我想要返回的标记是:

<li>Analyst</li>
<li>Cousins</li>
<li>Egg</li>
<li>Therapist</li>

我一直在搜索 Liquid 文档,我想我可以循环遍历并将它们分解成一个新数组 split 然后应用 sort,但实际做的方式这让我完全摸不着头脑。

如有任何帮助,我们将不胜感激。谢谢。

试试这个解决方案:

{% for tag in site.data.people %}
   {% for item in tag %}
   <li>
      {{ item }}
   </li>
   {% endfor %}
{% endfor %}

首先,您的json无效。我的 jekyll 似乎更喜欢 :

[
    {
        "name" : "George Michael",
        "topics" : ["Egg", "Cousins"],
        "contact" : [
            {
                "email" : "name@web.com",
                "twitter" : "@name"
            }
        ]
    },
    {
        "name" : "Tobias",
        "topics" : ["Analyst", "Therapist"],
        "contact" : [
            {
                "email" : "name@web.com",
                "twitter" : "@name"
            }
        ]
    }
]

不过,我觉得这个解决方案很好。请注意,第一个 for 循环应该创建一个没有重复项的主题数组。

{% comment %}Create an empty array for topics{% endcomment %}
{% assign topics = "" | split: "/" %}

{% for author in site.data.people %}
  {% for topic in author.topics %}

    {% comment %} As we don't want duplicates in our "topics" list we test it {% endcomment %}
    {% if topics contains topic %}
      {% comment %} Do nothing. Could have used unless, but I find if else more expressive. {% endcomment %}
    {% else %}
      {% assign topics = topics | push: topic %}
    {% endif %}

  {% endfor %}
{% endfor %}

Here you have a nice list which you can loop in : {{ topics | inspect }}