在我的帖子的前沿问题上,我有“类别”,这是一个数组。
我正在寻找一种基于类别数组中的第一个元素来过滤帖子的方法。
例如,如果我有两个职位的前沿问题,如:
title: Post Number One
categories:
- first post ever
- cool stories和
title: Post Two
categories:
- cool stories我想要一种过滤类别的方法,其中“酷故事”只返回"Post 2“,因为”酷故事“显示为数组的第一个元素。
发布于 2018-08-02 07:07:44
这是一个信息体系结构(IA)问题。
让我们使用Jekyll的category/categories内部工作来表示我们的IA。
如果您定义这样的帖子:
---
title: "My post"
category: "main category"
categories:
- other
- wat!
# ... more front matter variables
---类别/类别如下:
post.category => main category
post.categories =>
- other
- wat!
- main category现在,如果您想使用category过滤您的文章,使用exp滤波器,您可以这样做:
{% 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>发布于 2018-08-02 02:52:23
有几种方法可以实现这个特性。其中之一是:
在_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 that have the first category of "cool stories"
{% include first-category.html category = "cool stories" %}
## End上面的代码将只显示以“酷故事”为第一类的帖子。
https://stackoverflow.com/questions/51643545
复制相似问题