Filter Collection Items by page metadata

こ雲淡風輕ζ 提交于 2020-01-05 06:01:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!