I'm looping through a Matrix field called Documents. The matrix has three fields:

  • Document (an asset field)
  • Document Title (plain text field)
  • Document Type (a category field)

I need to loop through the matrix and output all the rows, but grouped by Document Type. This seems like it should work:

{% set grouped = entry.documents | group('documentType.title') %}

{% for categoryTitle, groupedRows in grouped %}
    TITLE HERE: {{ categoryTitle }}

    {% for document in groupedRows %}
        <br/>{{ document.documentTitle }}
    {% endfor %}
{% endfor %}

The problem is that {{ categoryTitle }} is blank. Nothing in it. The code runs, but the key is blank. The grouped rows are populated.

What's wrong?

2 Answers 2


That documentType in your group filter returns a criteria model prepared to query for categories related to that Matrix block. Use the first() method to try and get the first element matching your criteria and you can now access a property like the category’s title.

{% set grouped = entry.documents|group('documentType.first().title') %}

But this is also dangerous, as it might happen that a Matrix block does not have a category assigned (may be that this category got deleted). Here’s how you could improve it and write the code a bit more defensively.

{% set grouped = entry.documents|group('{ documentType.first() ? documentType.first().title : 'No categories }') %}

I'm guessing that you'd like {{ categoryTitle }} to be the current groups documentType.title?

If so, I would output document.documentType for the first document in each group using {% if loop.first %}.

Complete code suggestion would be:

{% set grouped = entry.documents|group('documentType.first().title') %}

{% for groupedRows in grouped %}
  {% for document in groupedRows %}
    {% if loop.first %}
      {{ document.documentType }}
    {% endif %}
    {{ document.documentTitle }}
  {% endfor %}
{% endfor %}

EDIT: updated to use carlcs group filter suggestion.

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.