使用 != 逻辑过滤 Liquid/Jekyll 数组?
Filter a Liquid/Jekyll array with != logic?
我正在使用 Jekyll 构建一个站点,并尝试使用 Liquid 逻辑在每个 post 的末尾创建一个 'Recent Posts' 数组。
我希望此数组包含您当前所在页面的所有 post , 和 post 除外。
所以,我开始于:
{% for post in site.posts limit:2 %}
{% if post.title != page.title %}
//render the post
{% endif %}
{% endfor %}
这有效,只是我的 limit: 2
导致了问题。由于 Liquid 限制 before if
逻辑,如果它确实遇到标题等于当前页面标题的 post,它将(正确地)不呈现它,但是它将考虑限制 "satisfied" - 我最终只有 1 个相关 post 而不是 2 个。
接下来我尝试创建自己的 post 数组:
{% assign currentPostTitle = "{{ page.title }}" %}
{% assign allPostsButThisOne = (site.posts | where: "title" != currentPostTitle) %}
{% for post in allPostsButThisOne limit:2 %}
//render the post
{% endfor %}
这不起作用,因为我无法让 where
过滤器接受 !=
逻辑。
我怎样才能成功解决这个问题?
您可以使用计数器:
{% 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>
正如您所提到的,您只错过了这段代码:
{% assign allPostsButThisOne = (site.posts | where: "title" != currentPostTitle) %}
{% assign allPostsButThisOne = (site.posts | where_exp:"post", "unless post.title contains currentPostTitle") %}
我正在使用 Jekyll 构建一个站点,并尝试使用 Liquid 逻辑在每个 post 的末尾创建一个 'Recent Posts' 数组。
我希望此数组包含您当前所在页面的所有 post , 和 post 除外。
所以,我开始于:
{% for post in site.posts limit:2 %}
{% if post.title != page.title %}
//render the post
{% endif %}
{% endfor %}
这有效,只是我的 limit: 2
导致了问题。由于 Liquid 限制 before if
逻辑,如果它确实遇到标题等于当前页面标题的 post,它将(正确地)不呈现它,但是它将考虑限制 "satisfied" - 我最终只有 1 个相关 post 而不是 2 个。
接下来我尝试创建自己的 post 数组:
{% assign currentPostTitle = "{{ page.title }}" %}
{% assign allPostsButThisOne = (site.posts | where: "title" != currentPostTitle) %}
{% for post in allPostsButThisOne limit:2 %}
//render the post
{% endfor %}
这不起作用,因为我无法让 where
过滤器接受 !=
逻辑。
我怎样才能成功解决这个问题?
您可以使用计数器:
{% 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>
正如您所提到的,您只错过了这段代码:
{% assign allPostsButThisOne = (site.posts | where: "title" != currentPostTitle) %}
{% assign allPostsButThisOne = (site.posts | where_exp:"post", "unless post.title contains currentPostTitle") %}