2

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) %}
3

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 Jun 30 '15 at 8:35

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.