4

I have a matrix field with two different block types and I want create a conditional to check if one of the blocks is not empty show it and if it is show the other. This is not working:

{% for block in entry.page.type('text, intro') %}
    {% if block.type.text != "" %}
        <h3>{{ block.text }}</h3>
    {% else %}
        {{ block.intro }}
    {% endif %}
{% endfor %}

Thanks!

2
  • Wouldn't it be cleaner to show all the blocks in the field? How can you make sure there is a block with the other type just because there is no block with the first type? If your field contains matrix elements from both types, what should happen then? Apr 3, 2018 at 19:44
  • This is for my search results so I just want to show one or the other. If it contained both it would just show text.
    – fodney
    Apr 3, 2018 at 19:46

1 Answer 1

5

You can fetch the number of entries for the first type, check if you receive an empty array if so fetch matrix blocks of type B

Craft 2

{% set blocksTypeOne = entry.matrixFieldHandle.type('blockTypeHandle1').find() %}
{% if blocksTypeOne|length %}
     // blocks with type A exists
{% else %}
    {% set blocksWithTwo = entry.matrixFieldHandle.type('blockTypeHandle2').find()
    // do something with them
{% endif %}

Update Craft 4 has finally dropped the .find() method

{% set blocksTypeOne = clone(entry.matrixFieldHandle).type('blockTypeHandle1').all() %}
{% if blocksTypeOne|length %}
    // blocks with type A exists
{% else %}
    {% set blocksWithTwo = clone(entry.matrixFieldHandle).type('blockTypeHandle2').all()
    // do something with them
{% endif %}
2
  • This technique no longer works as of Craft 4. Anyone have a solutions that works in Craft 4? Aug 2 at 21:54
  • Craft 3 deprecated the .find() method, you need to use .all() now. The rest can be basically the same Aug 7 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.