1

My entry content is displayed like this:

{% for block in entry.postContent.all() %}
  <div class="my-4">
        {% if block.type == 'text' %}
      {{ block.text }}
    {% elseif block.type == 'image' %}
      {% for image in block.image.all() %}
        <img src="{{ image.url }}" alt="{{ image.title }}" />
      {% endfor %}
    {% endif %}
  </div>
{% endfor %}

I want to display some other things in the middle of this content but have no idea how I can do it. Maybe someone have any thoughts?

2
  • You seem to only call 1 block here (limit(1)) so where do you need to inject content exactly?
    – Oli
    Commented Mar 11, 2021 at 12:43
  • My bad.. I tried put limit over there but it doesn't change anything. That code displays my content. Everything is one block so I was thinking maybe I can count <p> somehow and after 50% of them insert lines that I want.. Commented Mar 11, 2021 at 13:10

1 Answer 1

1

There is a loop variable available within your for loop which you might be able to use here (docs). This starts at 1 and increment everytime your loop runs.

Using loop.index, you could do something like this:

{# Fetch your blocks #}
{% set blocks = entry.postContent.all() %}

{# Counts how many blocks you have in total #}
{% set totalBlocks = blocks | length %}

{# Divide your totalBlocks by 2 and round to find the 50% mark in your content #}
{% set halfwayPoint = (totalBlocks / 2) | round %}

{% for block in blocks %}
    <div class="my-4">

        {# When you reach halfway, inject #}
        {% if loop.index == halfwayPoint %}
            the content you want to inject
        {% endif %}

        {% if block.type == 'text' %}
            {{ block.text }}
        {% elseif block.type == 'image' %}
            {% for image in block.image.all() %}
                <img src="{{ image.url }}" alt="{{ image.title }}" />
            {% endfor %}
        {% endif %}
    </div>
{% endfor %}
2
  • It doesn't work since we put all the content in one block. My idea was to use <p> tags that seperate every paragraph. Maybe it's possible to make it work in this way? Commented Mar 11, 2021 at 18:57
  • I'm still looking for solution how to count <p> elements from matrix blocks and display in the middle. So far I went to this: {% set blocks = entry.postContent.all() %} {% set block = blocks[0] ?? null %} {% set count = block.text | substringCount('<p>') %} {% set halfwayPoint = (count / 2) | round %} I get half number of <p> but cannot get content displayed after that... Commented May 24, 2021 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.