按前端数组值列出集合中的项目

时间:2018-06-15 23:14:29

标签: jekyll liquid

我有一个Jekyll网站,其中包含一个集合colleges,我希望按自定义rankings前端内容属性对其进行排序和显示。以下是集合中项目的示例:

---
title: Example College
score: 88
rankings:
  - top accredited colleges
  - most affordable
---

...

---
title: Sample College
score: 75
rankings:
  - most affordable
  - best online programs
---

...

---
title: Example University
score: 75
rankings:
  - top accredited colleges
  - best online programs
---

我想将不同的排名显示为列在他们下面的大学的标题,如下:

top accredited colleges
- Example College
- Example University

most affordable
- Example College
- Sample College

best online programs
- Sample College
- Example University

我尝试使用Liquid的group_by过滤器,如下所示:

{% assign groups = site.colleges | group_by: "rankings" %}
{% for group in groups %}
    <h2>{{ group.name }}</h2>
    <ul>
        {% for college in group.items %}
            <li>{{ college.title }}</li>
        {% endfor %}
    </ul>
{% endfor %}

但是这似乎是将rankings前置物质与完整数组的精确匹配分组,而不是分离出它包含的不同值:

<h2>[top accredited colleges, most affordable]</h2>
<ul>
    <li>Example College</li>
</ul>

<h2>[most affordable, best online programs]</h2>
<ul>
    <li>Sample College</li>
</ul>

<!-- etc -->

如何从输出中的rankings前端数组中分离出各个值?

1 个答案:

答案 0 :(得分:1)

这可以解决问题:

{% assign allRankings = site.colleges | map: "rankings" %}
{% assign rankingArray = "" | split:"" %}
{% for rankings in allRankings %}
  {% assign rankingArray = rankingArray | concat: rankings | uniq %}
{% endfor %}
{% for ranking in rankingArray %}
  <h2>{{ ranking | capitalize }}</h2>
  <ul>
  {% for college in site.colleges %}
    {% if college.rankings contains ranking %}
    <li>{{ college.title }}</li>
    {% endif %}
  {% endfor %}
  </ul>
{% endfor %}