按页面元数据过滤收集项目

时间:2018-03-29 18:25:18

标签: jekyll liquid

上下文

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

_product-categories/filename1.md

---
- title
- uuid
---

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

page.html

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

目标

我想在页面上显示这些product-categories标题(来自集合元数据)。由于这些项目是通过文件名保存在前面的,所以不应该这样吗?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

{% 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>