1

I'm trying to merge a field name prefix with entry.section to make a dynamic field handle. I'm guessing I'm setting the sectionMatrix variable incorrectly, causing the code to fail without error. Any tips would be greatly appreciated.

Channels:

  • News
  • Press

Each channel has is own matrix field, with different blocks:

  • entryMatrixNews
  • entryMatrixPress

Template Code:

{% set newsSectionIds = craft.entries.section('news').ids() %}
{% set pressSectionIds = craft.entries.section('press').ids() %}
{% set entryIds = newsSectionIds|merge(pressSectionIds) %}
{% set entries = craft.entries.id(entryIds) %}

{% for entry in entries %}
   {% set sectionMatrix = 'entry.entryMatrix' ~ entry.section %}
   {# sectionMatrix then equals either entry.entryMatrixNews or entry.entryMatrixPress #}

   {% for block in sectionMatrix %}
      {# my matrix code #}
   {% endfor %}

{% endfor %}
2

The Twig attribute function solved this for me. Thanks to @tom-bauer

Revised Template Code:

{% set newsSectionIds = craft.entries.section('news').ids() %}
{% set pressSectionIds = craft.entries.section('press').ids() %}
{% set entryIds = newsSectionIds|merge(pressSectionIds) %}
{% set entries = craft.entries.id(entryIds) %}

{% for entry in entries %}

    {% set sectionMatrix = attribute(entry, "entryMatrix"~entry.section) %}

    {% for block in sectionMatrix %}

        {# my matrix code #}

    {% endfor %}

{% endfor %}
| improve this answer | |
  • You can also use the subscript syntax: entry["entryMatrix"~entry.section]. – carlcs Feb 24 '16 at 14:44
  • Thank you. This works perfectly, and is slightly shorter too. – Andrew F Feb 24 '16 at 15:37

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.