【问题标题】:Filter a Liquid/Jekyll array with != logic?用 != 逻辑过滤 Liquid/Jekyll 数组?
【发布时间】:2016-03-11 17:28:04
【问题描述】:

我正在使用 Jekyll 构建一个站点,并尝试使用 Liquid 逻辑在每个帖子的末尾创建一个“最近的帖子”数组。

我希望这个数组包含所有帖子除了您当前所在页面的帖子。

所以,我开始:

{% for post in site.posts limit:2 %}
  {% if post.title != page.title %}
    //render the post
  {% endif %}
{% endfor %}

这可行,只是我的limit: 2 引起了问题。由于Liquid限制了if逻辑之前,如果它确实遇到标题等于当前页面标题的帖子,它将(正确)不呈现它,但它会认为限制“满足” -我最终只有 1 个相关帖子而不是 2 个。

接下来我尝试创建自己的帖子数组:

{% assign currentPostTitle = "{{ page.title }}" %}
{% assign allPostsButThisOne = (site.posts | where: "title" != currentPostTitle) %}

{% for post in allPostsButThisOne limit:2 %}
  //render the post          
{% endfor %}

这不起作用,因为我无法让 where 过滤器接受 != 逻辑。

我怎样才能成功解决这个问题?

【问题讨论】:

    标签: jekyll liquid


    【解决方案1】:

    你可以使用计数器:

    {% assign maxCount = 2 %}
    {% assign count = 0 %}
    <ul>
    {% for post in site.posts %}
      {% if post.title != page.title and count < maxCount %}
        {% assign count = count | plus: 1 %}
        <li>{{ post.title }}</li>
      {% endif %}
    {% endfor %}
    </ul>
    

    【讨论】:

    • 太好了,这正是我所需要的——一种思考解决问题的全新方式。谢谢!
    【解决方案2】:

    正如你所提到的,你只错过了这段代码:

    {% assign allPostsButThisOne = (site.posts | where: "title" != currentPostTitle) %}
    

    我尝试将containsunless 一起使用

    {% assign allPostsButThisOne = (site.posts | where_exp:"post", "unless post.title contains currentPostTitle") %}
    

    【讨论】:

    • 语法错误。这样做的标准方法是:` {% assign allPostsButThisOne = (site.posts | where_exp: "item", "item.title != 'currentPostTitle'") %} `
    • inigomedina 的语法几乎对我有用,我只需要删除括号
    猜你喜欢
    • 2014-10-20
    • 2017-04-25
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    相关资源
    最近更新 更多