Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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 %}
share|improve this answer
    
Perfect. So simple :) Thank you. –  Mark Aug 13 at 14:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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