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

时间:2016-12-07 12:42:57

标签: arrays for-loop split jekyll liquid

我正在开发一个Jekyll项目,该项目在people.json文件夹中有一个名为_data的文件。 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 %}

返回:

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

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

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

我一直在搜索Liquid文档,我想我可以通过split循环并将它们分成一个新的数组,然后应用sort,但实际上这样做的方式就是躲避我完全。

非常感谢任何帮助。谢谢。

2 个答案:

答案 0 :(得分:0)

试试这个解决方案:

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

答案 1 :(得分:0)

首先,你的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 }}