Jekyll - 获取属于多个分类的所有文章

5
我想循环遍历所有被分配到类别“foo”和类别“bar”的帖子...
{% for post in site.categories.foo and in site.categories.bar %}

这是可能的吗?

在我的情况下,“foo”作为“bar”的“父”类别... /foo/bar/_posts

谢谢

3个回答

4

不必查看每篇文章并使用“或”来匹配,您可以通过第一个标签进行筛选,然后查找第二个(第三个、第四个、第五个......)标签:

{% for post in site.categories.fizz%}
    {% if post.categories contains "buzz" and post.categories contains "bang" %}
         <!--post has categories fizz AND buzz AND bang-->
        <li><a href="{{ post.url }}">{{ post.title }}</a></li>
    {% endif %}
{% endfor %}

这比遍历每一篇文章更有效率,它建立了一个关系而不是一个关系。


3
可以完全实现:循环遍历所有帖子,然后选择所需的帖子。
{% for post in site.posts %}
    {% if post.categories contains "foo" or post.categories contains "bar" %}
        <li><a href="{{ post.url }}">{{ post.title }}</a></li>
    {% endif %}
{% endfor %}

我尝试过这个,但是我的for循环索引会出错,而我正在使用它来编写一些分隔符元素。 - empire29
在我的使用情况下,它应该是一个“and”,而不是一个“or”。 - empire29
请问您能描述一下您的帖子是如何存储的,以及您的分类是如何定义的吗? - user2490676
我已经完成了。它们按照原始问题中显示的路径进行组织。 - empire29
是的,但你的YALM长什么样子?你的_config.yml文件中有关于URL的特定内容吗? - user2490676

0

在Jekyll中使用Where Expression过滤器。

Jekyll Liquid Filter Docs

Where Expression, 选择数组中所有表达式为真的对象。 3.2.0

{{ site.members | where_exp:"item", "item.projects contains 'foo'" }}

因此,在我的网站上,我执行了以下操作:

_includes/clippings.html
...
{% capture _filter %}item.tags contains '{{ include.tag }}'{% endcapture %}

{% for clip in site.clippings | where_exp: 'item', _filter %}
  {{ clip.do_stuff }}
  # more html and stuff
{ endfor }

{% include clippings.html tag='foo' %}

在这种情况下,我需要动态指定过滤器标签。Clippings只是像posts一样的集合。
如果您想按多个静态标签进行过滤,可以尝试以下方法:
{% for post in site.posts | where_exp: 'item', "item.tags contains 'foo'" | where_exp: 'item', "item.tags contains 'bar'" %}
  {{ post.do_stuff }}
{ endfor }

如果您想要进行多个动态筛选标签,那么您需要做类似于我上面所做的捕获操作。

我还没有测试过这个,但它应该可以通过任意数量的筛选标签来过滤帖子。


{% assign posts = site.posts %}
{% filter_tags = 'foo, bar, buzz' | slipt: ', ' %}

{% for tag in filter_tags %}
  {% capture _filter %}item.tags contains '{{ tag }}'{% endcapture %}
  {% assign posts = posts | where_exp: 'items', _filter %}
{% endfor %}

{% for post in posts %}
  {{ post.do_stuff }}
{% endfor %}

然而,在那一点上,循环遍历整个内容并检查每个帖子可能更有效率。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接