[英]How to check if `folderitem` is the first array element in Jekyll (Liquid)?
下面的代码应该为 PDF output 中的每个页面添加一个<h1>
。基本上,它遍历定义我的指南的 YAML 文件,如果当前页面的 URL 与 8837018528 块中的 URL 匹配,它将放置<h1>
标签中父块的title
键。
{% 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 %}
问题是当前代码对每个页面都这样做,如下所示:
<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>
我需要另一个条件检查,比如“if folderitem
is the first one”,只有当项目是列表中的第一个时,条件逻辑的 rest 才会继续,结果是:
<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>
选择第一项的语法是什么? first
似乎是为了返回数组的第一项,这似乎不适用于检查当前项是否是我正在使用的 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
想法来自: jekyll/liquid:在模板中从 hash 给定密钥访问值
无法测试它,但这样的事情可以帮助你进入循环吗?
{% assign first_url= site.data.sidebars[page.sidebar].entries | where: "url", page.url | first %}`
我想到了。 代替
{% if folderitem.url == page.url %}
我能够使用
{% if folderitem.url == page.url and forloop.first == true %}
事实上,这个附加条件确实准确地检查了我想要检查的内容——数组项是否在前面。 讽刺的是(因为我在写文档?),问题是https://shopify.github.io/liquid/上的 Liquid 文档不完整,而https://shopify.dev/api/liquid/上的 Liquid 文档/更全面。
这是关于forloop.first
的文档。 在这里,我还了解到我可以使用forloop.index
(基于 1)、 forloop.index0
等属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.