【问题标题】:Filter Collection Items by page metadata按页面元数据过滤集合项目
【发布时间】:2018-03-29 18:25:18
【问题描述】:

上下文

我有一个名为 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标题(来自集合元数据)。既然项目是通过文件名保存在front matter中的,这不应该是可能的吗?

【问题讨论】:

  • 你试过什么代码?我相信这是可能的。

标签: jekyll liquid


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 这很好用。谢谢你,大卫!我花了很长时间才知道什么我需要做什么,但是由于缺乏关于collection 级别可用属性的文档(文档讨论了relative_path,但不是relative_directory),我无法将这些碎片拼凑在一起。
猜你喜欢
  • 1970-01-01
  • 2021-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 2019-10-22
  • 2021-02-10
  • 1970-01-01
相关资源
最近更新 更多