Eleventy:集合中数据的输出子集

问题描述

我有一个产品集合,我希望从该产品集中输出图像轮播。我的首要任务包括以下内容……

---
carousel:
  - image: '/assets/img/img.jpg'
    imageAlt: 'text'
  - image: '/assets/img/img-02.jpg'
    imageAlt: 'text'
  - image: '/assets/img/img-03.jpg'
    imageAlt: 'text'
  - image: '/assets/img/img-04.jpg'
    imageAlt: 'text'
  - image: '/assets/img/img-05.jpg'
    imageAlt: 'text'
---

然后我的局部对象叫轮播。

{% for item in collections.products %}
  <figure class="outer-5by3">
    <img loading="lazy" class="inner-5by3" src="{{ item.data.carousel.image }}" alt="{{ item.data.carousel.imageAlt }}">
  </figure>
{% endfor -%}

但是,结果输出的src和alt属性为空吗?而且我不明白为什么?我唯一的猜测是,这与我试图遍历前端物质的子集有关吗?

在同一个产品系列中,我在前端定义了一个主图像,即...

img_main:
  image: '/assets/img/img.jpg'
  imageAlt: 'text'

使用以下模板...

{% for product in collections.products -%}
  <figure class="outer-1by1">
    <img class="inner-1by1" src="{{ product.data.img_main.image }}" width="160" height="143" alt="{{ product.data.img_main.imageAlt }}" loading="lazy" />
  </figure>
{% endfor -%}

这将产生所需的输出

<figure class="outer-1by1">
  <img class="inner-1by1" src="/assets/img/img.jpg" width="160" height="143" alt="text" loading="lazy" />
</figure>

为什么我认为item.data.carousel.image可以工作?

解决方法

通过设置两个循环来完成此工作,第一个循环遍历整个集合。第二个是数据子集(数组)。

{% set allProductPosts = collections.featuredProduct -%} // First we call all posts in the collection
<div class="product_carousel">
  <div class="product_carousel_featured">
    {% for item in allProductPosts -%} // We then loop through the collection
    {% for carousel in item.data.carousel %} // Then loop through the subset (array) of data
    <div class="product_carousel_cell">
      <figure class="outer-5by3">
        <img class="inner-5by3" src="{{ carousel.image }}" alt="{{ carousel.imageAlt }}" loading="lazy" />
      </figure>
    </div>
    {% endfor -%}
    {% endfor -%}
  </div>
</div>

感谢Raymond Camden推动我寻求解决方案。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...