1

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()

4

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.

|improve this answer|||||
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.

|improve this answer|||||
  • 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) – Matthias Redl-Mann Jul 19 '17 at 6:44

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.