9

When looping through a matrix, is there aquick way to check whether or not the block has a particular field (not if the field is empty, but if the field exists at all).

I have a matrix with ~20 block types, 12 or so have a field called blockTitle. For in-page nav, I'd like to loop through all the blocks and just output blockTitle for those that do have it. I could do this with a conditional for block.type, but am wondering if there's a simpler check (in case we add more block types in the future, don't want to have to update the conditional every time).

Using {% if block.blockTitle %} will kick back "Craft\MatrixBlockModel and its behaviors do not have a method or closure named "blockTitle"." for block types without that field, so that's a no go.

Tks.

15

This should work:

{% if block['blockTitle'] is defined %}
    // Do your thing
{% endif %}
2

It is possible to set custom field parameters on Matrix block queries (→ Craft 2.3 release notes). And looking for non empty fields is possible with :nonempty: (also not documented but mentioned in the 2.0 release notes).

{% set blocksWithTitle = entry.myMatrixField.myTitleField(':notempty:') %}

{% for block in blocksWithTitle %}
    {{ block.myTitleField }}
{% endfor %}
2

The most reliable method i've found to test if a matrix field is defined is using the length twig filter:

{% if entry.myMatrixField | length %}
  {% for block in entry.myMatrixField %}
    <p>Matrix blocks here.</p>
  {% endfor %}
{% else %}
  <p>Matrix not defined.</p>
{% endif %}

More on this in the Craft CMS docs here.

  • I believe that entry.myMatrixField.first() (or entry.myMatrixField.one() in Craft v3) is more efficient, because it doesn't have to count them all up. – ianp May 3 '18 at 11:06

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.