5

Just wondering if there's a way to return the matrix block number during the loop?

For example:

{% for block in entry.myMatrixField %}
  {% if block.type == "quote" %}
    <blockquote class="quote{{GET_BLOCK_NUMBER}}">
      <p>{{ block.quote }}</p>
    </blockquote>
  {% endif %}
{% endfor %}

Might return something like this:

<blockquote class="quote1">
  <p>Curabitur aliquet quam id dui posuere blandit.</p>
</blockquote>
<blockquote class="quote2">
  <p>Curabitur aliquet quam id dui posuere blandit.</p>
</blockquote>
<blockquote class="quote3">
  <p>Curabitur aliquet quam id dui posuere blandit.</p>
</blockquote>

Thanks, Mark

1 Answer 1

8

Yes that's possible, all Twig loops have a loop variable:

loop.index - The current iteration of the loop. (1 indexed)
loop.index0 - The current iteration of the loop. (0 indexed)

Example:

{% for block in entry.myMatrixField %}
  {% if block.type == "quote" %}
    <blockquote class="quote{{ loop.index }}">
      <p>{{ block.quote }}</p>
    </blockquote>
  {% endif %}
{% endfor %}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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