TransWikia.com

Optimizing working Code — reduce the loop

Craft CMS Asked by Simon__ on September 21, 2020

I have the current situation and already a solution for it. But I’m not feeling very well as it seem to have an unecessary loop?
Situation

Structure: itemCategories

Category A
Subcategory B
Subcategory C

Category D
Subcategory E

Channel: items

Item A
Item B
Item C

The entries in ‘items’ having a relation field to itemCategories. So I can select multiple categories within this field.
I render them as a navigation structure and it’s related content.

Now I have the problem that I often want to output give items grouped in it’s selected categories.
An item can be listed in multiple categories. Like:

CategoryA

Item B
Item C

Category D

Item A
Item B

This code snippet is based on outputting a search result:

  {# Get the search parameter from the call #}
  {% set searchQuery = craft.app.request.getParam('q') %}

  {# Fetch entries that match the search query #}
  {% set results = craft.entries()
      .search(searchQuery)
      .section('items')
      .all() %}

  {# Array to hold the categories from the found items #}
  {% set categories = [] %}

  {# I'm looping threw the search result and than loop over the category field in the item #}
  {# Than writing it into the created array #}
  
  {% for result in results %}
    {% for cat in result.category %}
        {% set categories = categories|merge([cat.id]) %}
    {% endfor %}
  {% endfor %}

  {# As it's possible the same category more than once I apply a unique filter #}
  {% set categories = categories|unique %}
  

  {# Now I loop over the unique list of categories #}
  {% for category_id in categories %}

      {% set category = craft.entries.section('categories').id(category_id).one %}

      <h1>{{category}}</h1>
      <hr>

      {# Inside the loop I go threw the search results again and output them if the current category is in the item's category field #}
      {% for result in results %}

        {% if category.id in result.category.ids() %}
            {{result.title}}<br>
        {% endif %}

      {% endfor %}

  {% endfor %}

As I said I feel like it’s a little bit overused. Perhaps someone has a smarter solution for it.

Regards
Simon

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP