1

I have a Matrix field setup. I want to be able to pull in the first Matrix block used to print a snippet, but only out of the blocks 'text' or 'textImage'. So the first one used, out of those two only.enter image description here

This is what I have but it's pulling in the textContent block regardless, even if the text block is first.

    {% set textBlock = entry.body.type('text').first() %}
    {% set textBlock2 = entry.body.type('textImage').first() %}


    {% if textBlock %}
        <p>{{ textBlock.textContent|hacksaw(chars='100', append='...') }}</p>

        {% else %}

        {% if textBlock2 %}

        <p>{{ textBlock2.text|hacksaw(chars='100', append='...') }}</p>
        {% endif %}

    {% endif %}
2

Give this ago.

It will grab the first block that is either "Text" or "Text Image" and then you can use a switch statement to output your template depending on the block type.

{% set firstTextBlock = entry.body.type(['text', 'textImage']).first() %}

{% switch firstTextBlock.type %}

    {% case 'text' %}
        <p>{{ firstTextBlock.textContent|hacksaw(chars='100', append='...') }}</p>

    {% case 'textImage' %}
        <p>{{ firstTextBlock.text|hacksaw(chars='100', append='...') }}</p>

{% endswitch %}
|improve this answer|||||
  • Doesn't like {% switch firstTextBlock.type %} error: Impossible to access an attribute ("type") on a null variable – sarah3585 Feb 13 '17 at 17:22
  • 1
    It sounds like you might not have any block matching the "text" or "textImage" type in your matrix. That said, I should have wrapped the switch in an if statement to allow for that. {% if firstTextBlock %} _switch_ {% endif %} – Tom Feb 13 '17 at 19:07

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.