1

I need to check if the first block in a Matrix field matches one of an array of types. Here's a simplified version of my code:

{% if entry.newsArticleContent.one().type in ['fullWidthImage', 'imageGroup'] %}
    yep
{% else %}
    nope
{% endif %}

{{ entry.newsArticleContent.one().type }} outputs fullWidthImage, but the above conditional outputs nope.

The following outputs yep:

{% if 'fullWidthImage' in ['fullWidthImage', 'imageGroup'] %}
    yep
{% else %}
    nope
{% endif %}

so I know it's not a problem with the if statement or the fact that I'm checking the value against an array.

Is there a reason why the value of entry.newsArticleContent.one().type can't be used in this context?

Thanks!

EDIT: Thought I should mention that I'm looping through all blocks in the Matrix field later on in the same template. Just in case that's relevant.

1

When you call entry.newsArticleContent.one().type, what you're getting is an instance of craft\models\MatrixBlockType (https://github.com/craftcms/cms/blob/develop/src/models/MatrixBlockType.php)

It just happens to have a __toString() method that will print out the handle when it's requested, but the if comparison you're doing is using the entire MatrixBlockType instance.

What you're looking for is:

{% if entry.newsArticleContent.one().type.handle  in ['fullWidthImage', 'imageGroup'] %}

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.