How Do I Select the second instance of a certain block type We use a matrix field for the article content on our site. We have different blocks for different content (text, images, embed etc..) and we have optional fields that are outside of the matrix that  only need to be defined once, like a related article or place.

My current code to output the matrix is as follows

{% for block in entry.postBody %}

{% include 'blog/blocks/_' ~ block.type ignore missing with {"block":block} only %}

{% endfor %}


I want to float my related related restaurant section (which is optional) after either


the second instance of a text block


or


the last text block. 


Some of my blocks are elements that take up the entire width of the section, so I want to attach it to a text block so that it floats neatly alongside the text.

How would I select the second or last instance of a certain block type within my for loop?
You could save that second text block's ID to a variable and compare against that in your text partial:

_entry.html:

{% set textBlocksIds = entry.postBody.type('text').ids() %}
{% set secondTextBlockId = textBlocksIds|length &gt;= 2 ? textBlocksIds[2] : textBlocksIds[1] %}

{% for block in entry.postBody %}
    {% include 'blog/blocks/_' ~ block.type ignore missing with {
        'block': block,
        'secondTextBlockId': secondTextBlockId
    } only %}
{% endfor %}


blog/blocks/_text.html:

{% if block.id == secondTextBlockId %}
    {% include 'blog/partials/_restaurants' %}
{% endif %}