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?

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.

  • #3 worked for me! Thanks very much. – Tyssen Dec 27 '19 at 3:42

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.