2

Is there a way to dynamically iterate over a matrix block's fields such that the template doesn't need to know the field handles? This doesn't work:

{% for block in entry.myMatrixField %}
    {% for field in block %}
        {# do something with field #}       
    {% endfor %}
{% endfor %}

This seems like a simple thing to want to do but I haven't figured out a way to do it.

5

Not sure what you want to do with the fields, but you can access them through fieldLayout.

{% for block in entry.myMatrixField %}

    {% for field in block.getFieldLayout().getFields() %}

        {# get properties #}
        {{ field.getField().name }}
        {{ field.getField().handle }}
        {{ field.getField().id }}

        {# get value #}
        {% set handle = field.getField().handle %}
        {{ block[handle] }}

    {% endfor %}

{% endfor %}

You do kind of need to know what the field types are, in order to know how to display them. {{ block[handle] }} will fail for instance if one of the fields is an 'Entry' field, because you can't convert an ElementCriteriaModel to a string. To check the field type you can use field.getField().type;

| improve this answer | |
  • It's a bit more verbose than I was hoping for, but does what I need. Thank you. – ray hatfield Feb 3 '15 at 20:30
  • Get rid of the extra junk and it's just 5 lines! Fyi... see this answer for more complete example. – Douglas McDonald Feb 3 '15 at 21:18
  • I just meant that block[block.getFieldLayout().getFields()[0].getField().handle] seems like a long dig to get to the value. – ray hatfield Feb 3 '15 at 22:22

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.