根据 Jekyll 数组中的第一个参数过滤内容

Filtering content based on first parameter in array in Jekyll

在我帖子的 Front Matter 中,我有 "categories" 这是一个数组。

我正在寻找一种方法来根据类别数组中的第一个元素过滤帖子。

例如,如果我有两个帖子的 Front Matter,例如:

title: Post Number One 
categories:
   - first post ever
   - cool stories

title: Post Two
categories:
- cool stories

我想要一种过滤类别的方法,其中 "cool stories" 将 return 仅 "Post Two",因为 "cool stories" 显示为数组的第一个元素。

有多种方法可以实现此功能。其中之一是:

使用以下代码在 _includes 中创建一个名为 first-category.html 的新包含文件:

{% assign chosen_category = include.category %}

{% for post in site.posts %}
{% for category in post.categories.first %}
{% if category == chosen_category %}
  {{ post.title }}
{% endif %}
{% endfor %}
{% endfor %}

然后,在您列出第一个类别的 post 的页面中,只需包含上述文件并传递所选类别名称:

## Post that have the first category of "cool stories"

{% include first-category.html category = "cool stories" %}

## End

上面的代码将只显示 posts,其中 "cool stories" 作为 posts 的 front-matter 中的第一个类别。

这是一道信息架构 (IA) 题。

  • 任何 post 必须归入主要 类别
  • post 可以归入多个“类别

让我们用 Jekyll 的 category/categories 内部工作来代表我们的 IA。

如果你这样定义 post :

---
title:  "My post"
category: "main category"
categories:
  - other
  - wat!
# ... more front matter variables
---

Category/categories 将可用为:

post.category => main category
post.categories =>
  - other
  - wat!
  - main category

现在,如果您想使用 category 来过滤您的 post,请使用 group_by and where_exp filters,您可以这样做:

{% assign category = "main category" %}

{% comment %} #### Grouping posts by 'main' category {% endcomment %}
{% assign grouped = site.posts | group_by: "category" %}
{{ grouped | inspect }}

{% comment %}#### Get our category group{% endcomment %}
{% assign categoryPosts = grouped | where_exp: "group", "group.name == category" | first %}
{{ categoryPosts | inspect }}

{% comment %} #### All interesting posts are now in categoryPosts.items {% endcomment %}
{{ categoryPosts.items | inspect }}

{% comment %} #### We can now sort and loop over our posts {% endcomment %}

{% assign sorted = categoryPosts.items | sort: "whateverKeyYouWantToSortOn" %}
<ul>
{% for post in sorted %}
 <li>
  <a href="{{ site.baseurl }}{{ post.url }}">{{ post.title }}</a>
  <br>Category : {{ post.category }}
  <br>Categories :
  <br><ul>{% for c in post.categories %}
   <li>'categorie' {{ forloop.index }} - {{ c }}</li>
  {% endfor %}</ul>
 </li>{% endfor %}
</ul>