2

I have a matrix field shaped as follows:

  • MatrixField
    • Block ( just 1 blocktype )
      • Field1
      • Field2
      • Field3
      • Field4
      • FieldN

I want to loop through all the fields inside a block, check if the field is set and other stuff. How can I do it?

1 Answer 1

6
  1. Check if the matrixField is populated:

    {% if entry.matrixField|length %}{% endif %}

  2. There are two options to pull out fields from a block type.

    Option A: use a for-loop pointed at your Matrix field

    // If you want to output block of a certain type
    {% if entry.matrixField|length %} 
        {% for block in entry.matrixField.type('yourBlock') %}
            {{ block.field1 }}
            {{ block.field2 }}
            {{ block.fieldN }}
        {% endfor %}
    {% endif %}
    
    // OR multiple types
    {% if entry.matrixField|length %} 
        {% for block in entry.matrixField %}
            {% if block.type == "yourBlock" %}
                {{ block.field1 }}
                {{ block.field2 }}
                {{ block.fieldN }}
            {% elseif block.type == "yourBlock1" %}
                {{ block.field1 }}
                {{ block.field2 }}
                {{ block.fieldN }}
            {% endif %}
        {% endfor %}
    {% endif %}
    

    Option B: use simplified method of a for-loop

    {% if entry.matrixField|length %} 
        {% set yourBlock = entry.matrixField.type('yourBlock') %}
        {% for block in entry.matrixField %}
            {% switch block.type %}
                {% case "yourBlock" %}
                    {{ block.field1 }}
                    {{ block.field2 }}
                    {{ block.fieldN }}
            {% endswitch %}
        {% endfor %}
    {% endif %}
    

Also check Craft's documentation about Matrix Fields.

Your Answer

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

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