1

I'd like to wrap a series of block.type (images and description) in a div. So at the first iteration of this block type it needs to parse the start of the div. In the last iteration of this block type it needs to close the div.

I tried something like this, if there is a next block from the same type but no previous block, start the div and visa versa:

{% for block in entry.detailMatrix %}
    {% if block.type=="images" %}
        {% if block.next().type == 'images' and not block.prev().type == 'images'%}
            <div class="section" >
        {% endif %}
            {{block.image}}
            </div>
        {% if block.prev().type == 'images' and not block.next().type == 'images'%}
            </div>
        {% endif %}
    {% endif %}
{% endfor %}
noregt
  • 1,062
  • 9
  • 16

3 Answers3

3

You need to define the block previous/next variables outside of your for loop. Also you should check for the last element in the loop.

You can find a great working example on the happy lager demo website (https://github.com/pixelandtonic/HappyLager).

The relevant code part is here: https://github.com/pixelandtonic/HappyLager/blob/master/craft/templates/_includes/article_body.html.

Tom Bauer
  • 1,327
  • 7
  • 14
1

In addition to Tom's excellent answer, you could also tackle this with a simple if-loop-index condition. Have a look at this answer

Matt P
  • 1,538
  • 1
  • 9
  • 24
1

Tom's answer got me in the right direction. I ended up using this:

{% for block in entry.detailMatrix %}
   {# If there is a block type images, but no previous block images, start the div #}
   {% if block.type == 'images' and block.prev().type != 'images'%}
        <div class="section" >
    {% endif %}

    {% if block.type=="images" %}
        {{block.image}}
    {% endif %}

    {# If there is a block type images, but no next block images, close the div. Place in the bottom if there are more block types #}
    {% if block.type == 'images' and block.next().type != 'images'%}
        </div>
    {% endif %}
{% endfor %}

Instead of using "not" using != worked better

noregt
  • 1,062
  • 9
  • 16