【问题标题】:How to limit posts filtered by front matter?如何限制按前端过滤的帖子?
【发布时间】:2023-04-05 19:33:01
【问题描述】:

我有 Jekyll 博客,其中有些帖子有“特色图片”,而有些帖子没有。

特色图片在帖子的开头部分定义如下:featured-image: http://path/to/img

在存档页面上,我想抓取三个具有特色图片的最新帖子并显示它们。

我想这需要一个 if 语句、一个计数器和一个循环,但我无法让这个为我工作:

<ul id="archive-featured">
  {% assign count = '0' %}
  {% if count < '4' %}
    {% for post in site.posts %}
      {% if post.featured-image == true %}
        {{ count | plus: '1' }}
        <li><a href="{{ post.url }}"><img src="{{post.featured-image}}" />{{ post.title }}</a></li>
      {% endif %}
    {% endfor %}
  {% endif %}
</ul>

我错过了什么?

【问题讨论】:

  • 我也在寻找类似的东西 - > 如果计数为 0,我将完全跳过显示“相关”标题。所以我想先计数,然后循环如果 count > 0,则通过它们。

标签: jekyll


【解决方案1】:

您的 YAML 问题看起来不错,但我不确定您是否需要计数分配才能完成这项工作。尝试使用 limit 来限制您在存档页面上分配的帖子数量。您也无需为 {% if %} 语句分配“真”值即可工作:

<ul id="archive-featured">
{% for post in site.posts limit:3 %}
  {% if post.featured-image %}
    <li>
      <a href="{{ post.url }}">
        <img src="{{ post.featured-image }}" />
        {{ post.title }}
      </a>   
    </li>
  {% endif %}
{% endfor %}
</ul>

我相信这些帖子会自动显示在最近的帖子中,因此不需要在那里做额外的工作。希望这会有所帮助!

【讨论】:

  • 嗨,朱莉娅!感谢回复!我尝试了一个较早的变体,但如果最近的一篇帖子没有特色图片,就会出现问题。仅显示两个帖子。我想展示三个最新的帖子(有特色图片)!这就是我尝试使用计数器 + 循环的原因。
  • 啊!我会用{% if %} 语句包装&lt;img&gt;,而不是整个&lt;li&gt;。限制应该处理显示三个最近的问题。
  • 但是它会显示两个图像和一个链接。我想要发生的是,如果一个帖子没有特色图片,我们会跳过它并检查下一个并继续,直到我们收集了三个带有特色图片的帖子。然后打印那个。这有意义吗?
【解决方案2】:

一个很晚的答案:
我认为问题在于{{count | plus: 1}}。这不只是输出计数+ 1,而不是分配它吗? 您可以通过在 forloop 结束之前分配一个新变量来解决此问题

<ul id="archive-featured">
  {% assign count = 0 %}
  {% if count < 4 %}
    {% for post in site.posts %}
      {% if post.featured-image == true %}

        <li><a href="{{ post.url }}"><img src="{{post.featured-image}}" />{{ post.title }}</a></li>
{% count | plus: 1 %}
      {% endif %}
    {% endfor %}
  {% endif %}
</ul>

可能很有趣的解决方法: 如果你在前面添加另一个简单的语句,比如featured: true,你可以使用 where 过滤器来只选择那些帖子。 (遗憾的是 where 过滤器似乎不适用于比较)

<ul id="archive-featured">
  {% assign posts=site.posts | where "featured", "true" %}
    {% for post in posts | limit: 3%}
        <li><a href="{{ post.url }}"><img src="{{post.featured-image}}" />{{ post.title }}</a></li>
    {% endfor %}
</ul>

【讨论】:

    猜你喜欢
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2022-01-18
    • 2021-10-26
    相关资源
    最近更新 更多