问题
Context
I have a jekyll collection called product-categories
in which each file has the following metadata in front matter:
_product-categories/filename1.md
---
- title
- uuid
---
I have a page whose front matter contains filenames from this collection (collection array selections are saved by their filenames with front matter)...
page.html
---
product-categories:
- filename1
- filename2
---
[list of product-categories to be displayed here]
Goal
I want to display the title (from the collection metadata) of these product-categories
on the page. Since the items are saved in the front matter by their filename, shouldn't this be possible?
回答1:
You can do like this :
{% 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>
来源:https://stackoverflow.com/questions/49562787/filter-collection-items-by-page-metadata