I'm trying to check to see if a particular category (In a loop) exists in a query submitted from a search form.

At the moment I'm doing this inside a 'childCategory' loop...

{% for childCategory in childCategories %}

    {% for category in query %}{% if childCategory.slug == category.slug %} checked{% endif %}{% endfor %}

{% endfor %}

EUGH right?

Is there a better way (Surely!) to check to see if the cateogry exists? I've tried the length and indexOf filters as well as an IN conditional. Nothing works.

The query is being set like this:

{% set query = craft.request.getParam('category') %}
{% set queryCategories = craft.categories.group('opportunities').slug(query) %}

2 Answers 2


I would construct an array of the category slugs outside of your childCategories loop (using twig's merge filter:

{% set queryCatSlugs = [] %}
{% for category in query %}
  {% set queryCatSlugs = queryCatSlugs|merge([category.slug]) %}
{% endfor %}

Then your childCategories loop can use twig's containment operator (in) for the test:

{% for childCategory in childCategories %}
  {% if childCategory.slug in queryCatSlugs %}
    ... matches ...
  {% endif %}
{% endfor %}
  • That worked perfectly! Wasn't aware of the merge filter, will remember that one! Thanks for the help!
    – Jason Mayo
    Commented Jun 30, 2015 at 8:35

In Craft 3 you don't have to iterate through the chidlCategories manually, you could use the column filter instead, like this:

{% set queryCatSlugs = childCategories.all() | column('slug') %}
{% if slugToCheck in queryCatSlugs %}
{% endif %}

Your Answer

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

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