TransWikia.com

Determine if entry has a specific category

Craft CMS Asked on September 27, 2021

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.

One Answer

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' }}

Correct answer by Oli on September 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP