Why does my Twig for loop not get a Key? 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 %}
        &lt;br/&gt;{{ 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?
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.