【问题标题】:Jekyll - Get all posts that are in multiple categoriesJekyll - 获取多个类别的所有帖子
【发布时间】:2014-04-14 02:15:51
【问题描述】:

我想遍历所有分配类别“foo”和类别“bar”的帖子..

{% for post in site.categories.foo and in site.categories.bar %}

这可能吗?

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

谢谢

【问题讨论】:

    标签: jekyll liquid


    【解决方案1】:

    完全有可能:遍历所有帖子,然后选择想要的帖子:

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

    【讨论】:

    • 我试过了,但是我的 forloop.index 下架了,我用它来写一些分隔符。
    • 在我的用例中,它是一个“和”而不是“或”
    • 您能否描述一下您的帖子的实际存储方式以及您的类别是如何定义的?
    • 我做到了。它们按路径组织,如原始问题所示。
    • 是的,但是您的 YALM 看起来如何?您的 _config.yml 中是否有关于 url 的特定内容?
    【解决方案2】:

    您可以通过第一个标签进行过滤,然后查找第二个(以及第三、第四、第五...)标签,而不是查看每个帖子并匹配 或:: p>

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

    这比遍历每个帖子更有效,它设置了 and 关系而不是 or 关系。

    【讨论】:

      【解决方案3】:

      在 Jekyll 中使用 Where 表达式过滤器。

      Jekyll Liquid Filter Docs

      在哪里表达, 选择数组中表达式为真的所有对象。 3.2.0

      {{ 网站成员 | where_exp:"item", "item.projects 包含 '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' %}
      

      在这种情况下,我需要动态指定过滤器标签。而剪报就像帖子一样只是一个集合。

      如果您想通过多个静态标签进行过滤,您可以执行以下操作:

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

      但是,在那时循环遍历整个内容并检查每个帖子可能会更有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-31
        • 2021-12-20
        • 2020-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多