1

I'm stumped on a basic concept for looping images. I'm using the plugin ImageOptimize with Imgix and Amazon S3. The code below works but only shows one image (when there's more for that field).

For the code below, how are you suppose to loop through the assets without showing the different srcset image sizes?

{% set optimizedImages = entry.clientWork.one().imgixTransforms %}        

    <picture>
        <source srcset="{{ optimizedImages.srcsetWebP() }}" 
            sizes="100vw"
            type="image/webp" />

        <img src="{{ optimizedImages.src() }}"
            srcset="{{ optimizedImages.srcset() }}"
            sizes="100vw" />
    </picture>
3

So the OptimizedImages field in ImageOptimize is added to your asset as a field (just like Entries can have fields), because it's added to your Asset Volume layout.

So you'd iterate through the images the same way you would iterate through any assets in Craft. I'm a little unclear on what part you're stuck on here? If you could clarify, I could help you more.

So let's say we have an Asset's field with a handle of heroImages, to output all of those images we'd do:

{% for heroImage in entry.heroImages.all() %}
    <img src="{{ heroImage.url }}">
{% endfor %}

So then let's say you have an OptimizedImages field with a handle of optimizedImages that's in your Asset Volume's layout, so it becomes a field that's in your Assets. Then we could just do:

{% for heroImage in entry.heroImages.all() %}
    <img src="{{ heroImage.optimizedImages.src() }}" srcset="{{ heroImage.optimizedImages.srcset() }}">
{% endfor %}

And it'll output all of the same images as in the previous example, but using an optimized srcset of the images.

| improve this answer | |
  • I know this is basic but I'm confused on how I would iterate through the assets in Craft 3. If I wrap the code above with {% for asset in entry.clientWork %} then it shows the same image multiple times (showing the various sources from the srcset) instead of showing the three images I have for that field just once. – Jon Livingston Mar 7 '18 at 21:15
  • I amended my original answer with some more details for you. – andrew.welch Mar 17 '18 at 0:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.