2

I'm grouping search results by section, based on Aaron Berkowitz's answer to this question. My code looks like this:

{% set entries = craft.entries({search: {query: keywords} }) %}
{% set entriesBySection = entries | group('section') %}

{% for section, entries in entriesBySection %}
    <h2>{{ section }}</h2>
    <ul>
        {% for entry in entries %}
            <li>{{ entry.title }}</li>
        {% endfor %}
    </ul>
{% endfor %}

That works great but I need to show the sections in a specific order, and merge some sections into one. So I'd end up with, for example:

  • News
  • Products
  • Reports
  • Other (everything else combined)

Any idea how to do this?

Thanks loads for any help!

1 Answer 1

2

You could do this in a few steps (warning: this is untested code):

1) Define an array of the sections you cited, in the correct order:

{# Define a list of the sections you want to display in the correct order #}
{% set sections = ['news', 'products', 'reports'] %}

2) Identify the entries that do not belong in any of these sections:

{# Create an array of entries that do not belong to any of the sections above #}
{% set otherEntries = [] %}

{# We first loop on the entries by section to identify the "other" entries #}
{% for section, entries in entriesBySection %}
    {% if section in sections %}
        {% for entry in entries %}
            {% set otherEntries = otherEntries|merge([entry])}
        {% endfor %}
    {% endif %}
{% endfor %}

3) Display all the entries of each section in the correct order

{# Loop on the sections in the right order #}
{% for section in sections %}
    {# Obtain all the entries for the current section #}
    {% set entries = entriesBySection[section] %}
    {% for entry in entries %}
        ...
    {% endfor %}
{% endfor %}

4) Display the rest of the entries

{# Finally display the "other" entries #}
{% for entry in otherEntries %}
    ...
{% endfor %}

Your Answer

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

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