4

I have a masonry type image grid layout and I need to specify a different image transform for just the 2nd and fourth images in this grid.

Does the image ID relate to the order or to the specific image? How could I include a conditional in my code to output the largeIndexHalf image transform for the 2nd and 4th image?

{% set asset = entry.portraits %}
{% if asset | length %}
{% for asset in entry.portraits %}
<div class="item"><img src="{{ asset.getUrl('largeIndex') }}" /></div>
{% endfor %}
{% endif %}
6

You could do that like so:

{% for asset in entry.portraits %}
    {% if loop.index == 2 or loop.index == 4 %}
        {% set transform = 'largeIndexHalf' %}
    {% else %}
        {% set transform = 'largeIndex' %}
    {% endif %}
    <div class="item"><img src="{{ asset.getUrl(transform) }}" /></div>
{% endfor %}

or more simply (making use of the containment operator (in) and the ternary operator (? :):

{% for asset in entry.portraits %}
    {% set transform = loop.index in [2, 4] ? 'largeIndexHalf' : 'largeIndex' %}
    <div class="item"><img src="{{ asset.getUrl(transform) }}" /></div>
{% endfor %}
1
3

To better understand, do you want transform for all even iterations on the array? If so, Twig's cycle function should do what you want:

{% set asset = entry.portraits %}
{% if asset | length %}
   {% for asset in entry.portraits %}
      {% set transform = cycle(['largeIndex', 'largeIndexHalf'], loop.index0) %}
      <div class="item"><img src="{{ asset.getUrl(transform) }}" /></div>
   {% endfor %}
{% endif %}

Edit

Rereading the question and Brandon's answer, I may have misinterpreted that you do indeed just want the 2nd and 4th image. I'll leave my answer for posterity for people looking to do an even / odd thing though.

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.