1

I have a situation where Matrix within Matrix would be ideal, but instead we've ended up with a Matrix row that has pairs of fields up to a maximum of 6:

quote1
attribution1
…
quoteN
attributionN
…
quote6
attribution6

Rather than work through each pair…

{% if matrixBlock.quote1|length %} {# quote 1 stuff #} {% endif %} … {% if matrixBlock.quote6|length %} {# quote 6 stuff #} {% endif %}

…I thought I might be able to use a variable reference to numbers 1 to 6:

{% set quotes = [1, 2, 3, 4, 5, 6] %}

{% for n in quotes %}
    {% set nText = 'quote' ~ n %}
    {% set nCite = 'attribution' ~ n %}

    <blockquote>
        {{ matrixBlock.nText|md }}
        <cite>{{ matrixBlock.nCite }}</cite>
    </blockquote>
{% endfor %}

…but although {{ dump(nText) }} confirms the reference string is being parsed correctly, the string is clearly invalid as a field reference.

Is there a way to get this done to achieve a nice terse template (not the end of the world if I can't)?

I have a sense that Twig's attribute function might help, but I can't join the dots.

1
  • If you're looking to nest Matrix fields I highly recommend the Neo plugin. May 15 '18 at 22:59
1

Figured it out:

{% for n in [1, 2, 3, 4, 5, 6] %}
    {% if attribute(matrixBlock, 'quote' ~ n)|length %}
    <blockquote>
        {{ attribute(matrixBlock, 'quote' ~ n) }}
        <cite>{{ attribute(matrixBlock, 'attribution' ~ n) }}</cite>
    </blockquote>
    {% endif %}
{% endfor %}
1

You can also use the subscript syntax which is slightly more terse. And to iterate over a sequence of numbers, you can use the .. operator instead of listing the whole array.

{% for n in 1..6 %}
    {% if matrixBlock['quote' ~ n]|length %}
    <blockquote>
        {{ matrixBlock['quote' ~ n] }}
        <cite>{{ matrixBlock['attribution' ~ n] }}</cite>
    </blockquote>
    {% endif %}
{% endfor %}
0

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.