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

1 Answer 1

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 %}
2
  • You can also use the subscript syntax: entry["entryMatrix"~entry.section].
    – carlcs
    Feb 24, 2016 at 14:44
  • Thank you. This works perfectly, and is slightly shorter too.
    – Andrew F
    Feb 24, 2016 at 15:37

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.