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

如何在Jekyll(Liquid)中判断folderitem是否为数组首个元素?

问题:仅为文件夹下首个页面添加H1标签

现有一段Liquid代码,原本用于在PDF输出中为页面添加<h1>标签:它会遍历定义指南的YAML配置文件,当当前页面URL与YAML块中的URL匹配时,将父文件夹的title放入<h1>标签内。

现有Liquid代码

{% assign sidebar = site.data.sidebars[page.sidebar].entries %}
    
{% for entry in sidebar %}
  {% for folder in entry.folders %}
    {% if folder.title and folder.type != "navi" and folder.type != "frontmatter" %}
      {% for folderitem in folder.folderitems %}
        {% if folderitem.url == page.url %}
<h1 class="post-title-main" id="{{page.permalink | replace: '/', '' }}">{{ folder.title }}</h1>
        {% endif %}
      {% endfor %}
    {% endif %}
  {% endfor %}
{% endfor %}

当前问题

这段代码会给每个匹配URL的页面都输出<h1>,示例输出如下:

<h1>The Title I Want to Put in the H1</h1>
<h2>The Title of the Page Which I *Do* Want the <H1> to Appear Above</h2>
. . .
<h1>The Title I Want to Put in the H1</h1>
<h2>The Title of the Page Which I *Don't* Want the <H1> to Appear Above</h2>

需求

需要添加条件判断,仅当当前folderitem是所在数组的首个元素时,才输出该<h1>标签,最终期望输出:

<h1>The Title I Want to Put in the H1</h1>
<h2>The Title of the Page Which I *Do* Want the <H1> to Appear Above</h2>

参考YAML结构

对应的YAML配置结构示例:

entries:
- title:
  pdftitle: foobar.pdf
  product:
  version:
  folders:

  - title:
    output: pdf
    type: frontmatter
    folderitems:

    - title:
      url: /titlepage.html
      output: pdf
      type: frontmatter

  - title: My Amazing Guide
    output: web
    type: navi
    folderitems:

    - title: Home
      url: /index.html
      output: web

- title: The Title I Want to Put in the H1
    url: /section/page/index.html
    output: web, pdf
    folderitems:

    - title: The Title of the Page Which I *Do* Want the <H1> to Appear Above
      url: /section/page/some-page.html
      output: web, pdf

    - title: The Title of the Page, Which I *Don't* Want the <H1> to Appear Above
      url: /section/page/another-page.html
      output: web, pdf

解决方案

在Liquid循环中,可使用forloop.first变量判断当前迭代的元素是否为循环的第一个元素。只需在原有的URL匹配条件后,追加and forloop.first即可实现需求。

修改后的Liquid代码

{% assign sidebar = site.data.sidebars[page.sidebar].entries %}
    
{% for entry in sidebar %}
  {% for folder in entry.folders %}
    {% if folder.title and folder.type != "navi" and folder.type != "frontmatter" %}
      {% for folderitem in folder.folderitems %}
        {% if folderitem.url == page.url and forloop.first %}
<h1 class="post-title-main" id="{{page.permalink | replace: '/', '' }}">{{ folder.title }}</h1>
        {% endif %}
      {% endfor %}
    {% endif %}
  {% endfor %}
{% endfor %}

修改后,仅当页面是对应folder下的第一个folderitem时,才会输出父文件夹的H1标题,其他页面不会重复输出该标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 16:20:29