按页面元数据过滤 Collection 个项目

Filter Collection Items by page metadata

上下文

我有一个名为 product-categories 的 jekyll collection,其中每个文件在前面都有以下元数据:

_product-categories/filename1.md

---
- title
- uuid
---

我有一个页面,其前面内容包含来自此 collection 的文件名(collection 数组选择按其文件名和前面内容保存)...

page.html

---
product-categories:
  - filename1
  - filename2
---
[list of product-categories to be displayed here]

目标

我想在页面上显示这些product-categories标题(来自collection元数据)。由于项目按文件名保存在前面,这不是可能的吗?

你可以这样做:

{% comment %} --- Get product-categories collection's datas --- {% endcomment %}
{% assign collection = site.collections | where: "label", "product-categories" | first %}

{% comment %} --- collection's docs root path --- {% endcomment %}
{% assign collection_path = collection.relative_directory | append: "/" %}

<ul>
{% for cat in page.product-categories %}

  {% comment %} --- expected file path --- {% endcomment %}
  {% assign filepath = collection_path | append: cat | append:".md" %}

  {% comment %} Look for files that have path == filepath.
                As "where" filter return an array,
                we pick the first and only item in array  {% endcomment %}
  {% assign file = site.product-categories | where:"path", filepath | first %}

  {% if file %}
    <li>{{ file.title }}</li>
  {% else %}
    {% comment %} --- error in front matter list ---{% endcomment %}
    <li>No file match for <strong>{{ cat }}</strong> : file at <strong>{{ filepath }}</strong> not found</li>
  {% endif %}

{% endfor %}
</ul>