Use Twig's batch filter with conditional 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' %}
  &lt;div class="wrapper"&gt;
    &lt;div class="row"&gt;
      {% for block in row %}
        &lt;div class="text-center c6 med-c12 push-top-double"&gt;
          &lt;div class="section fill-grey-light rounded"&gt;
            &lt;div class="c12 grid-center"&gt;
              &lt;h3&gt;{{ block.titleText }}&lt;/h3&gt;
              {% if block.ctaUrl|length and block.ctaText|length %}
                &lt;a href="{{ block.ctaUrl }}" class="btn push-top"&gt;
                  {{ block.ctaText }}
                &lt;/a&gt;
              {% endif %}
            &lt;/div&gt; &lt;!-- .c --&gt;
          &lt;/div&gt; &lt;!-- .section --&gt;
        &lt;/div&gt; &lt;!-- .c --&gt;
      {% endfor %}
    &lt;/div&gt; &lt;!-- .row --&gt;
  &lt;/div&gt; &lt;!-- .wrapper --&gt;
{% endfor %}
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) %}
  &lt;div class="wrapper"&gt;
    &lt;div class="row"&gt;
      {% for block in row %}
        {# ... block code here ... #}
      {% endfor %}
    &lt;/div&gt; &lt;!-- .row --&gt;
  &lt;/div&gt; &lt;!-- .wrapper --&gt;
{% endfor %}