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

Jekyll循环遍历文章时如何获取指定序号(如第3条)的post内容

Jekyll 遍历循环时提取指定位置文章的方法

方法1:直接通过数组索引提取(无需遍历)

Liquid 中的数组默认从0开始计数,你要获取第3篇文章,直接取索引为2的元素即可:

{% assign third_post = paginator.posts[2] %}
<h2><a href="{{ third_post.url }}">{{ third_post.title }}</a></h2>

如果要提取非分页的全量文章第3篇,把paginator.posts替换为site.posts即可。

方法2:在循环内通过循环变量判断提取

如果你需要在遍历所有文章的逻辑中单独处理第3篇,可以用Liquid内置的forloop变量判断位置:

{% for post in paginator.posts %}
  <!-- forloop.index 从1开始计数,等于3时即为第3篇文章 -->
  {% if forloop.index == 3 %}
    <h2><a href="{{ post.url }}">{{ post.title }}</a></h2>
    <!-- 此处可添加第3篇的专属处理逻辑,比如加特殊样式标签等 -->
  {% endif %}
{% endfor %}

常用forloop参数说明:

  • forloop.index:当前循环次数,从1开始计数
  • forloop.index0:当前循环次数,从0开始计数
  • forloop.first:布尔值,判断是否是循环的第一个元素
  • forloop.last:布尔值,判断是否是循环的最后一个元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:18:01