4

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?

Jan Henckens
  • 335
  • 1
  • 11
  • 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 04 '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 04 '18 at 22:31
  • @RobinSchambach That seems to be working! Could you post it as the answer? :) – Jan Henckens Jun 05 '18 at 11:39

1 Answers1

4

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

Robin Schambach
  • 19,713
  • 1
  • 19
  • 44