【问题标题】:Exclude current post from recent posts query in Jekyll?从 Jekyll 的最近帖子查询中排除当前帖子?
【发布时间】:2016-11-05 21:31:54
【问题描述】:

这里有一个最近的帖子查询,其中包含最近 5 个帖子。

 {% for post in site.posts limit:5 %}
     <li>
    < a href="{{ post.url }}">{{ post.title }}</a>
     </li>
   {% endfor %}

但是,如果它是 5 个最新帖子之一,这也会显示当前帖子。我试图包含一个检查 URL 的 if 语句,但是如何将 +1 添加到限制变量?

P.S.:我在锚标签中加入了一个空格,所以它可以作为代码阅读

【问题讨论】:

    标签: jekyll liquid markup


    【解决方案1】:

    检查网址应该可以。只需循环六个项目并在找不到匹配项时隐藏最后一个。

    {% for post in site.posts limit:6 %}
      {% if post.url != page.url %} 
        {% if forloop.index < 6 or found %}
          <li>
            <a href="{{ post.url }}">{{ post.title }}</a>
          </li>
        {% endif %}
      {% else %}
        {% assign found = true %} 
      {% endif %}
    {% endfor %}
    

    代码的作用(一步一步):

    • 循环播放 6 个帖子
    • 检查帖子是否不是当前页面/帖子
    • 如果您处于循环/迭代 1 到 5 或您已找到当前项目*
    • 然后显示您循环/迭代的帖子

    *允许您循环/迭代第 6 号帖子

    【讨论】:

    • 请看Kais给出的答案……比这个答案更好。
    【解决方案2】:

    更好的选择是使用:

    {% assign posts = site.posts | where_exp:"post","post.url != page.url" %}
    {% for post in posts limit:5 %}
      <li>
        <a href="{{ post.url }}">{{ post.title }}</a>
      </li>
    {% endfor %}
    

    它的作用:

    • 创建一个名为 posts 的新变量。
    • 使用 where_exp 过滤器过滤掉与当前页面具有相同 URL 的帖子。
    • 循环遍历这个新变量,限制为 5(最多 5 个帖子)。

    【讨论】:

    • 你能解释一下你的代码是做什么的吗?仅代码的答案通常被认为是低质量的。查看接受的答案,他们如何详细解释它。这就是我们所需要的。
    猜你喜欢
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    相关资源
    最近更新 更多