You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Liquid中遍历site.posts数组前3项 适配Jekyll站点开发需求

解决方案

你之前在数组过滤器文档中没有找到对应功能,是因为limit属于Liquid循环的内置控制参数,不属于数组过滤器类别,无需手动写死下标,两种常见场景的实现方式如下:

场景1:从原site.posts前3项中过滤不符合要求的内容

直接在for循环语句后加limit:3即可,该参数会限制循环最多执行3次:

<h2>最近新增的礼物</h2>
<div class="posts">
    {% assign posts = site.posts %}
    {% for post in posts limit:3 %}
    {% unless post.list  %}
    <div class="post">
        <h3 class="post-title">
            <a href="{{ post.url | relative_url }}">
                {{ post.title }}
            </a>
        </h3>

        <time datetime="{{ post.date | date_to_xmlschema }}" class="post-meta">{{ post.date | date_to_string }}</time>

        <p class="post-excerpt">
          {% if post.description %}
            {{ post.description | strip_html }}
          {% else %}
            {{ post.excerpt | strip_html }}
          {% endif %}
        </p>
    </div>
    {% endunless %}
    {% endfor %}
</div>

如果前3项中存在post.list为真的内容,该方案最终输出的项数会少于3。

场景2:严格输出3个符合unless post.list要求的内容

新增计数变量统计符合条件的项数,满3个就终止循环:

<h2>最近新增的礼物</h2>
<div class="posts">
    {% assign posts = site.posts %}
    {% assign valid_count = 0 %}
    {% for post in posts %}
    {% unless post.list  %}
      {% if valid_count < 3 %}
    <div class="post">
        <h3 class="post-title">
            <a href="{{ post.url | relative_url }}">
                {{ post.title }}
            </a>
        </h3>

        <time datetime="{{ post.date | date_to_xmlschema }}" class="post-meta">{{ post.date | date_to_string }}</time>

        <p class="post-excerpt">
          {% if post.description %}
            {{ post.description | strip_html }}
          {% else %}
            {{ post.excerpt | strip_html }}
          {% endif %}
        </p>
    </div>
      {% assign valid_count = valid_count | plus: 1 %}
      {% else %}
        {% break %}
      {% endif %}
    {% endunless %}
    {% endfor %}
</div>

该方案会遍历site.posts直到凑够3个符合条件的内容就停止,不会冗余遍历全量数组。

内容的提问来源于stack exchange,提问作者user14488588

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:15:08