如何检查列表中是否存在值?

How to check if a value is present in a list?

我想获得 post 的列表,在他们的前言中有一个特定的标签 (*)

我尝试了下面的代码,它遍历了当前post页的所有标签(当前标签是t),然后遍历了所有posts( p) 检查他们是否有这个标签(出于调试原因只输出标题):

{% for t in page.tags %}
    {% for p in site.posts %}
        {% if t in p.tags %}
            {{ p.title }}
        {% endif %}
    {% endfor %}
{% endfor %}

{% if t in p.tags %} 似乎失败了(我来自 Python 背景,所以我试了一下)而且我在 liquid 中找不到 in 运算符。它退出了吗?

(*) 我提到了我想要实现的目标,以防有更直接的方法可以做到这一点,但我仍然对一般问题感兴趣。

按照您的示例,可以使用 contains 标签完成:

contains can also check for the presence of a string in an array of strings.

{% if product.tags contains "outdoor" %}   
This product is great for
using outdoors! 
{% endif %}

因此,要获取前言中具有特定标签的帖子列表(在本例中为带有标签 mytag 的帖子):

{% assign posts_with_mytag =  site.posts | where_exp:"item",
"item.tags contains 'mytag'" %}

{% for post in posts_with_mytag %}
<a href="{{post.url}}">{{post.title}}</a>
{% endfor %}

跟进@maracuny 的回答,为了完整性从我的问题中更正代码:

{% for t in page.tags %}
    {% for p in site.posts %}
        {% if p.tags contains t %}
            {{ p.title }}
        {% endif %}
    {% endfor %}
{% endfor %}