0

I have a landing page on my site where I want to list a group of sections that have entries. I also need to access the section handle of that same group of sections.

I am having problems getting the section handle for the sections.

Currently I get an error back that says impossible to access attribute ("handle") on a string variable.

        {% set specialEntries = craft.entries.section(['sec1','sec2','sec3']) %}

        {% set grouped = specialEntries|group('section') %}
        {% for section, specialEntries in grouped %}
            <h1>{{ section }} - {{ section.handle }}</h1>
        {% endfor %}   
1

In your example, you're attempting to use a SectionModel instance as the key for your grouped entries. This is not possible.

What actually happens behind the scenes is the group filter generates an object where the keys are the string value of the SectionModel instance [1], and the values are the EntryModels associated with that section.

There are a few ways of achieving your desired outcome. Here's one possibility (not tested):

{% set sections = craft.sections.getAllSections() %}
{% set entries = craft.entries.section(['first', 'second', 'third']) %}
{% set grouped = entries|group('section') %}

{% for sectionHandle, sectionEntries in grouped %}
    {% set groupSection = false %}
    {% for section in sections %}
        {% if section.name == sectionHandle %}
            {% set groupSection = section %}
        {% endif %}
    {% endfor %}

    {% if groupSection %}
        <h1>{{ groupSection.name }} - {{ groupSection.handle }}</h1>
    {% endif %}
{% endfor %}

[1]: The SectionModel::__toString method returns the name attribute.

  • Glad I could help 👍 – Stephen Lewis Feb 23 '17 at 21:51
  • Now that I have the sections outputting, I need to sort them. Ideally by structureId. I've tried applying supersort to the "grouped" query but I'm not getting the results I would expect. Any advice? – triplethreat23 Apr 7 '17 at 0:07
  • You should probably post a separate question for that. – Stephen Lewis Apr 7 '17 at 1:56

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.