# How do I pull out a total of 4 rows from all my matrix blocks?

I have an entry that has a matrix field, which has a table in it; I am trying to pull out 4 rows from the latest block, but if there aren't 4 rows then I would like it to pull out the remainder from the older blocks (So I always have 4 items displayed, even if the latest matrix block only has 1 table row in it).

This is what I have so far, but this is pulling out the latest 4 rows from EACH matrix block, so if I have 2 blocks it displays 8 items.

Does anyone know if what I'm trying to do is possible?

``````{% for entry in craft.entries.section('sectionName').find() %}
{% for block in entry.matrixField %}

{% if block.type == "blockType" %}

{% for row in block.tableField | slice(0, 4) %} <!-- I tried .limit(4) here too -->
{{ row.title }}
{% endfor %}

{% endif %}

{% endfor %}
{% endfor %}
``````

Any help is appreciated!

I am assuming you want four rows from each entry. I would do it like this using `{% break %}` from the break and continue plugin:

``````{% for entry in craft.entries.section('sectionName').find() %}
{# restart our count for the new entry #}
{% set numberOfRows = 0 %}

{% for block in entry.matrixField %}
{% if block.type == "blockType" %}
{% for row in block.tableField.limit(4) %}

{# bail if we've done our 4 rows #}
{% if 4 <= numberOfRows %} {% break %} {% endif %}

{{ row.title }}
{# done another row, count it #}
{% set numberOfRows = numberOfRows + 1 %}

{% endfor %}
{% endif %}

{# bail if we've done our 4 rows #}
{% if 4 <= numberOfRows %} {% break %} {% endif %}

{% endfor %}
{% endfor %}
``````

Or, slightly less efficiently (but maybe simpler), like this without that plugin:

``````{% for entry in craft.entries.section('sectionName').find() %}
{% set numberOfRows = 0 %}
{% for block in entry.matrixField %}

{% if block.type == "blockType" %}
{% for row in block.tableField.limit(4) %}

{% if numberOfRows < 4 %}
{{ row.title }}
{% set numberOfRows = numberOfRows + 1 %}
{% endif %}

{% endfor %}
{% endif %}

{% endfor %}
{% endfor %}
``````

I don't think you pull out the four rows from multiple matrix blocks with a single query.

• Cheers Marion, that second code snippet was perfect! – Lighty_46 Jan 4 '15 at 0:45