【问题标题】:Eleventy: Output subset of data in collection十一:输出集合中的数据子集
【发布时间】:2020-12-07 12:42:05
【问题描述】:

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

---
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 会起作用?

【问题讨论】:

  • 如果你 {{ item.data | log }} 你在终端看到了什么?
  • 啊酷,不知道这个新功能。这是你希望看到的吗? carousel: [{ image: '/assets/img/KB09-01.jpg', imageAlt: 'High temperature KB09 beam style Stirling Engine' }, { image: '/assets/img/KB09-02.jpg', imageAlt: 'Rear view of beam Stirling Engine showing crank' }, { image: '/assets/img/KB09-03.jpg', imageAlt: 'KB09 Stirling engine showing conrod and beam' }, { image: '/assets/img/KB09-04.jpg', imageAlt: 'Front view displacer piston of Stirling engine' }, { image: '/assets/img/KB09-05.jpg', imageAlt: 'Top view of brass heatsink on the Stirling engine' }],
  • 所以看结果,image.data.carousel 是一个数组,而不是一个对象。因此,当您执行 item.data.carousel.image 时,这是不对的。我相信您实际上想要遍历 item.data.cataosel,因为那是您的图像数组。

标签: eleventy


【解决方案1】:

通过设置两个循环来实现这一点,第一个循环遍历整个集合。第二,数据子集(数组)。

{% 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 引导我找到解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2018-06-16
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    相关资源
    最近更新 更多