2

On Craft 3 I am iterating over matrix elements and I need to check if a certain property "videoPoster" exists. It's an asset field, so I actually want to check its length, but I'am already failing to check if it's available...

"ce" is one block of my matrix, this is what I'm doing:

{{ ce.videoPoster is defined ? 'yes' : 'no' }}

Works, gives me a nice "Yes"

Anything else does not work:

{{ ce.videoPoster is defined and ce.videoPoster ? 'yes' : 'no' }}
{{ ce.videoPoster is defined and ce.videoPoster is not null ? 'yes' : 'no' }}
{{ ce.videoPoster is defined and ce.videoPoster | length ? 'yes' : 'no' }}

Exception: Calling unknown method: craft\elements\MatrixBlock::videoPoster()

What is the correct check? I just want to know if I can call ce.videoPost.one()

2 Answers 2

7

Just found the trick: When you access an object in array style, you can test via is defined

e.g.

{{ object['property'] is defined ? 'defined' : 'not defined' }}

and you will get reliable results.

1
  • I would like to stress that checking for defined using the dot notation E.G. {{ object.property is defined ? 'defined' : 'not defined' }} is also possible. This works multiple levels deep. Mar 7, 2023 at 16:23
1

So in general, for things like this, I think the null coalescing operator in Twig is really useful. Something like {% set myImage = entry.someImage ?? entry.someOtherImage ?? null %} will set myImage to the first thing that is defined and is not null, from left to right.

1
  • Thanks. I think this is helpful in some cases, but doesn't help here. I just want to know, if I can access the property, and if it contains at least one time (a selected asset) Jul 19, 2017 at 6:44

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.