3

Situation: I have a matrix with about 10 block types, 3 of which have a certain field. I want to check if the current block has that field.

The field in question is a dropdown with values in all 3 options.

I've tried:

  • {{ attribute(block, 'backgroundColor') is defined ? 'true' : 'false' }}

=> returns true for all blocks

  • {% if block.backgroundColor|length %}

=> errors out with Craft\MatrixBlockModel and its behaviors do not have a method or closure named "backgroundColor".

  • {% if block.backgroundColor is defined %}

=> same error as above

Anyone know how to do this?

  • 1
    Checking if the field is defined should work. Is it the missing "d" in this line? {% if block.backgroundColor is defined %} – Simon Kuran Jun 4 '18 at 20:16
  • 2
    Have you tried {% if block['backgroundColor'] is defined %} this might not make any sense since it's actually "wrong" (PHP wise) but Twig has a rare bug in certain cases and doesn't recognize the correct syntax properly – Robin Schambach Jun 4 '18 at 22:31
  • @RobinSchambach That seems to be working! Could you post it as the answer? :) – Jan Henckens Jun 5 '18 at 11:39
3

In certain cases Twig is unable to recognize the correct object oriented syntax with magic properties so {% if object.property is defined %} will still produce an error.

You can use {% if block['backgroundColor'] is defined %} it seems strange and would usually considered as wrong syntax (PHP wise) but it works in Twig

| improve this answer | |

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.