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 %}
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.

  • That's a great answer Tom! – Matt P Feb 23 '16 at 18:08
  • It got me in the right direction Tom. I already had tried placing it outside the block loop, but made an error in the syntax. – noregt Feb 24 '16 at 9:00
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

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

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.