2

With

{% for category in entry.categories.all() %}
    <a href="{{ category.url }}">{{ category.title }}</a> {{ not loop.last ? '| ' }}
{% endfor %}

How do I exclude a specific category from displaying?

1 Answer 1

2

I might be mistaken, but you can just insert an if block into your loop:

{% set excludedId = 1234 %}

{% for category in entry.categories.all() %}
  {% if category.id != excludedId %}
    <a href="{{ category.url }}">{{ category.title }}</a>
    {{ not loop.last ? '|' }}
  {% endif %}
{% endfor %}

That said, this will no longer know whether the "last" item in the loop was excluded. A better solution might be to trim down the collection before beginning the iteration:

{% set excludedId = 1234 %}

{% for category in entry.categories.all() | filter((c) => c.id != excludedId) %}
  <a href="{{ category.url }}">{{ category.title }}</a>
  {{ not loop.last ? '|' }}
{% endfor %}

This makes use of the filter filter, which you can pass a "function" of sorts to compare each ID to your excluded one. If the comparison is false, it'll remove it from the collection before the loop starts.

One last option (and possibly the best one) is to adjust the query itself, before it's run:

{% set excludedId = 1234 %}
{% set onlyDesiredCategories = entry.categories.id("not #{excludedId}").all() %}

{% for category in onlyDesiredCategories %}
  <a href="{{ category.url }}">{{ category.title }}</a>
  {{ not loop.last ? '|' }}
{% endfor %}

Instead of filtering down from the natural relations, this method attempts to adjust the ElementQuery instance provided by the relation field (entry.categories) by setting the id param to not 1234, meaning that ID will be excluded when the query is executed. I haven't actually tried this lat method, myself, so your mileage may vary.

1
  • #3 worked for me! Thanks very much.
    – Tyssen
    Dec 27, 2019 at 3:42

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.