Stuck on a problem at the moment… trying to output a Rich Text field (copy) from an entry. The copy is contained in a matrix field (so: Entry -> Matrix Field -> Copy Field) but I can’t access it no matter what I try.

The Matrix Field Type is genericContent, the entry is relatedContent and the copy field is simply named copy.

Here's the code I currently have, I've tried various other options but none work.

{% set entries = entry.relatedContent %}

{% for entry in entries %}
    {% switch entries|length %}
        {% case '1' %}
        {% case '2' %}
            <article class="t{% if loop.first %} t--tall{% endif %}">
                <div class="content">
                    <span class="subtitle">{{ entry.sectionTag.first }}</span>
                    <h1>{{ entry.title }}</h1>
                    <p>{{ entry.genericContent.copyMatrix.copy.first }}</p>
        {% case '3' %}
        {% case '4' %}
    {% endswitch %}
{% endfor %}

You're close! The relatedContent field is an ElementCriteriaModel, so you need to loop over it (or otherwise treat it somewhat like an array) to get to the entries.

The matrix field is also an array like thing, and you need to loop over it to get at the blocks. See here

Here is what I would do (assuming the matrix field handle is genericContent:

{% for oneRelatedContent in entry.relatedContent %}
  {% for block in oneRelatedContent.genericContent %}
    <article class="t{% if loop.first %} t--tall{% endif %}">
      <div class="content">
        <span class="subtitle">{{ oneRelatedContent.sectionTag.first }}</span>
        <h1>{{ oneRelatedContent.title }}</h1>
        {{ copy }}
  {% endfor %}
{% endfor %}

You want to use loop.index to tell you which matrix block this is. If you need to count the entries in relatedContent, you will need loop.parent.loop.index Loop variable

  • Thanks for the reply. I'm getting an error: Variable "copy" does not exist — I tried changing {{ copy }} to {{ oneRelatedContent.copy }} but that just outputs the title for some reason. The Matrix handle is genericContent and the Block Type is copyMatrix but changing {% for block in oneRelatedContent.genericContent %} to {% for block in oneRelatedContent.copyMatrix %} gives me this error: Craft\EntryModel and its behaviors do not have a method or closure named "copyMatrix".
    – Chrish
    Aug 8 '16 at 13:25
  • Got it — {{ block.copy }} outputs what I'm looking for
    – Chrish
    Aug 8 '16 at 13:35

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.