1

I am trying to make a grid of blocks using Twig. I have different types of blocks so I am using a conditional to test the block type and render different components per block type.

The problem I am having is I want to batch my blocks (columns) in twos so that I can have two blocks per row, so I can do {% for row in entry.curatedContentBlocks|batch(2) if row.type == 'halfWidthBlock' %}, add a row and then nest {% for block in row %} and add my block styles. This should work but when I try to test the block type with row.type, I get an error saying Key "type" for array with keys "0, 1" does not exist.. I'm thinking this is something to do with the batch filter returning an array.

I think the following code is the closest I've gotten, but I am still getting an error saying Key "1" for array with keys "2, 3" does not exist.. Here's the code:

{% for i, row in entry.curatedContentBlocks|batch(2) if row[i].type == 'halfWidthBlock' %}
  <div class="wrapper">
    <div class="row">
      {% for block in row %}
        <div class="text-center c6 med-c12 push-top-double">
          <div class="section fill-grey-light rounded">
            <div class="c12 grid-center">
              <h3>{{ block.titleText }}</h3>
              {% if block.ctaUrl|length and block.ctaText|length %}
                <a href="{{ block.ctaUrl }}" class="btn push-top">
                  {{ block.ctaText }}
                </a>
              {% endif %}
            </div> <!-- .c -->
          </div> <!-- .section -->
        </div> <!-- .c -->
      {% endfor %}
    </div> <!-- .row -->
  </div> <!-- .wrapper -->
{% endfor %}
1

I don't think you can test a conditional against a batch set like this. I think it's testing each batched set against the conditional instead of each item inside the batched sets which is what you're going for.

I would just create a new set of filtered matrix blocks and then batch the result.

{% set onlyHalfWidthBlocks = [] %}

{% for block in entry.curatedContentBlocks if block.type == 'halfWidthBlock' %}
  {% set onlyHalfWidthBlocks = onlyHalfWidthBlocks|merge([block]) %}
{% endfor %}

{% for row in onlyHalfWidthBlocks|batch(2) %}
  <div class="wrapper">
    <div class="row">
      {% for block in row %}
        {# ... block code here ... #}
      {% endfor %}
    </div> <!-- .row -->
  </div> <!-- .wrapper -->
{% endfor %}
  • Hey Sean, did this answer help? – Alex Roper Apr 1 '18 at 6:00

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.