【问题标题】:One variable for different collections in Jekyll to use in forloopJekyll 中不同集合的一个变量,用于 for 循环
【发布时间】:2023-04-03 19:41:01
【问题描述】:

我的 Jekyll 网站上有几个集合。我已将帖子导航添加到在每个帖子页面上显示计数器的集合之一:

{% assign testimonials = site.testimonials %}
{% assign page_order = 1 %}
{% for node in testimonials reversed %}
  {% if node.url == page.url %}
    {{ page_order }} from {{ forloop.length }}
  {% else %}
    {% assign page_order = page_order | plus: 1 %}
  {% endif %}
{% endfor %}

我想让这段代码不仅适用于site.testimonials,也适用于其他集合。我试图为这样的集合传递一个变量:

{% capture label %}{{ page.collection }}{% endcapture %}
{% assign collection = site.collections | where: "label",label | first %}
{% for node in collection reversed %}
  {% if node.url == page.url %}
    {{ page_order }} from {{ forloop.length }}
  {% else %}
    {% assign page_order = page_order | plus: 1 %}
  {% endif %}
{% endfor %}

但它不起作用。有什么方法可以为 Jekyll 中的所有集合传递一个变量,以便在帖子导航的 forloop 中使用?

【问题讨论】:

  • 什么不起作用?
  • @wasthishelpful 上面的第二个代码不起作用。我只有 page_order 和 forloop.length 的空格。我猜,它找不到与page.label对应的集合。

标签: jekyll liquid


【解决方案1】:

当您使用site.testimonials 访问集合时,您将获得集合的文档数组。

{{ site.testimonials | inspect }}

# output >> [#<Jekyll::Document ...>, #<Jekyll::Document ...>, ...]

当您在循环访问 site.collection 时访问集合时,您会收到该集合的对象:

{% assign collection = site.collections | where: "label",page.collection | first %}
{{ collection | inspect }}
# output >> { "output": true, "label": "collectionLabel", 
              "docs": [ doc1, docs2, ... ], "files": [], 
              "directory": "/path/to/collection", 
              "relative_directory": "_colectionDirectory" }

在你的情况下,你只需要替换:

{% for node in collection reversed %}

作者:

{% for node in collection.docs reversed %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多