I'm generating a list of all related categories of the entries listed on the page.

{% for entry in entries %}
    {% set categories = craft.categories.group('functieGroep').level(2).relatedTo(entry).all() %}
    {% nav category in categories %}
        <option value="{{ category.title }}">{{ category.title }}</option>
    {% endnav %}
{% endfor %}

This produces the list of categories. However, I want this list sorted by category.title and only show one occurrence of similar listed categories?


As is mentioned in multiple places, Twig is for viewing, not manipulating data. However, this should work.

We create an empty array, then loop through each entry's categories and if they aren't in the array, add them. Then finish up with a sort by title

{% set categories = [] %}
{% for entry in entries %}
  {% set entryCategories = craft.categories.group...all() %}
   {# notice the IF to combat duplicates #}
   {% for category in entryCategories if category not in categories %}
     {% set categories = categories|merge([category]) %}
   {% endif %}
{% endfor %}
{% nav category in categories|sort((a,b) => { a.title <=> b.title } %} {# reverse to b.title <=> a.title to change sort #}
{% endnav %}
| improve this answer | |
  • Unfortunately your solution still produces the same list with duplicates. – Robbie Post Dec 23 '19 at 15:33
  • @RobbiePost sorry it's been a while. I believe you may need to work with IDs when checking, rather than the objects themselves (yay programming) which should solve the issue? I think you should be able to change the IF to category.id not in categories|map(cat=>cat.id) if you are still having trouble with this, let me know and I can update my answer if it works – Seraphim Jester Jan 10 at 16:08

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.