1

I am using a supertable (or matrix) to create rows. In each row, I have a Category Field. Multiple categories can be selected for each matrix row. As I loop over each row, I want to determine if the category field in that row has a specific category selected.

Example:

Matrix Row1:
-> Colour (Category Field):
--> Red, Orange, Blue

Matrix Row2:
-> Colour (Category Field):
--> Red, Blue

In the above example, in Twig, when I render out the row, I want to know if that row should be "Orange" or not, based on whether or not the "Orange" category was selected in the "Colour" field.

I can loop through every selected category in the category field, and plaintext match against it (example below), but I wondered if there is a cleaner/simpler way to do this.

{% set colourFlag = false %}
{% for class in row.rowSettings.rowColour.all() %}
    {% set colourFlag = (class == "orange" ? true) %}
{% endfor %}            
{{ colourFlag == true ? "yes-orange" : "no-orange"}}

Any advice would be grateful.

1

You could explicitly try to fetch orange and check whether you get a result or not:

{{ row.rowSettings.rowColour.slug('orange').one() ? 'orange is set' : 'orange is not set' }}
1
  • YES! That's exactly what I was looking for. I knew there had to be a better way. Thank @oli ! – Adrian Jul 29 '20 at 16:39

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.