3

Code:

{% for block in entry.testimonials %}
  <div class="col-24 {% if loop.last %}gutter-bottom{% else %}gutter-bottom--none{% endif %}">
    <div class="section inner">
      <div class="col-17 {% if loop.index0 is not divisible by(2) %}last float-right {% endif %}">
        {% switch block.type %}

        {% case "testimonials" %}

          <h3>{{ block.personsName }}</h3>
          {{ block.quote }}
          </div>

          {% for asset in block.image %}

            <div class="col-7 circle-image-container {% if loop.index0 is divisible by(2) %}last{% endif %}">
              <img src="{{ asset.getUrl() }}"  alt="{{ asset.title }}"/>
            </div>

          {% endfor %}

        {% endswitch %}
    </div>
  </div>
{% endfor %}   

Can anyone point out why the...

loop.index0 is divisible by(2)

I have on the div around the image isn't working. I'm getting the 'last' class on everything. The one on the previous div is working fine.

What am I missing?

EDIT:

I've just realised it's in it's own image loop causing the problem. How can I get around this?

5

Forgive me if I'm wrong... by using loop.index0 is divisible by(2) are you trying to determine if the instance is odd or even?

  • 1st - returns false
  • 2nd - returns true
  • 3rd - returns false
  • 4th - returns true

If so Twig does support checking if the loop index is even or odd. Perhaps that would be better to use?

{% if loop.index is even %}Even{% endif %}

EDIT

I've just had a read of the Craft docs for the Case and Switch tags and found this:

If you’re using the {% switch %} tag inside of a {% for %} loop, you won’t be able to access Twig’s loop variable directly inside of the {% switch %} tag. Instead, you can access it like so:

{% for matrixBlock in entry.matrixField %}
    {% set loopIndex = loop.index %}

    {% switch matrixBlock.type %}

        {% case "text" %}

            Loop #{{ loopIndex }}

    {% endswitch %}
{% endfor %}
| improve this answer | |
  • Thanks, yes that is easier but I still have the same problem of it returning the same for all of them – sarah3585 Jun 8 '16 at 15:37
  • @sarah3585 Just updated my answer with some information I found on the Craft docs, perhaps that will resolve your issue? – Jamie Wade Jun 8 '16 at 15:43
4

What you want is not the loop variable of the inner loop around the image, but the loop variable of the outer loop. To get to the outer loop, use loop.parent. Try this:

{% if loop.parent.loop.index0 is divisible by(2) %}last{% endif %}
| improve this answer | |

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.