3

How do I group entries by section? I have search results:

{% set entries = allowedSearchableEntries.search(query).order('score').limit(100) %}

But I want to have

SECTION NAME entry 1 entry 4 entry 6

SECTION NAME entry 3 entry 12

etc.

1 Answer 1

6

You can use the Twig group filter.

{% set entries = allowedSearchableEntries.search(query).order('score').limit(100) %}

{% set entriesBySection = entries|group('section') %}

{% for section, entriesInSection in entriesBySection %}
    <h2>{{ section }}</h2>

    <ul>
        {% for entry in entriesInSection %}
            <li><a href="{{ entry.url }}">{{ entry.title }}</a></li>
        {% endfor %}
    </ul>
{% endfor %}
1
  • 1
    Brilliant! Do you know also how I could change the order of sections before doing the group filter? Currently it pulls from the section order in the CP.
    – 4midori
    Feb 20, 2017 at 17:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.