簡體   English   中英

如何檢查`folderitem`是否是 Jekyll (Liquid) 中的第一個數組元素?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM