2

What I'm trying to achieve: I would like the content editor to upload 2 images to use in a matrix block, one outputs at mobile and the other at desktop (they need to be different images due to art direction from landscape formate to portrait on mobile).

Here is the matrix field setup: enter image description here

Current twig:

{% for block in entry.workVisuals.all() %}
    {% if block.type == "imageContent" %}

        {% set relatedAssets = block.workImageMobile.all() %}
          {% for pic in relatedAssets %}

            {% set img = craft.imager.transformImage(pic, {
              mode: 'crop',
              width: 1920,
            }) %}

            {% set imgMob = craft.imager.transformImage(entry.workImageMobile, {
                mode: 'crop',
                width: 768,
                height: 1272,
            }) %}

            <picture>
              <source media="(max-width: 767px)" srcset="{{ imgMob }}">
              <source media="(min-width: 768px)" srcset="{{ img }}">
              <img src="{{ img.url }}" alt="{{ pic.title }}">
            </picture>
          {% endfor %}

      {% endif %}

So obviously this is outputting the mobile image for both as asked:

{% set relatedAssets = block.workImageMobile.all() %}

What do i need to do to use both in the <picture> tag?

1

It looks like you're looping through block.workImageMobile.all(), and that's not what you want to be doing.

You're only putting in one image into each, right, and they're paired?

So, You want the main for-loop for the blocks, then render the images in each block together "work image 1, work mobile image 1" then move to the next block, and the next image pair.

{% for block in entry.workVisuals.all() %}
    {% if block.type == "imageContent" %}

        {% set picDesktop = block.workImage.one() %}
        {% set picMobile = block.workImageMobile.one() %}

        {% set imgDesk = craft.imager.transformImage(picDesktop, {
            mode: 'crop',
            width: 1920,
        }) %}

        {% set imgMob = craft.imager.transformImage(picMobile, {
            mode: 'crop',
            width: 768,
            height: 1272,
        }) %}

        <picture>
            <source media="(max-width: 767px)" srcset="{{ imgMob }}">
            <source media="(min-width: 768px)" srcset="{{ imgDesk }}">
            <img src="{{ picDesktop.url }}" alt="{{ pic.title }}">
        </picture>
    {% endif %}
{% endfor %}

Also note - on the desktop size, you've got it set to crop, but only have a width set, you might want to add a height to that too. Otherwise, it might be better with a resize function.

1
  • Thank you so much for your time, that worked perfectly, and I'm a lot less confused now.
    – Tigertiger
    Jan 30 '20 at 9:37

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.