2

I would like to include a file on every block but the last three. How can I accomplish this?

2 Answers 2

2

Inside of a for-loop you have access to some special variables.

{% for block in entry.myMatrixField %}
    {% set isEndBlock = loop.revindex <= 3 %}

    {% if not isEndBlock %}
        {# do things #}
    {% endif %}
{% endfor %}

Another approach would be to change / override the default criteria of the Matrix field’s ElementCriteriaModel.

{% set blocksCount = entry.myMatrixField.count() %}
{% set isValid = blocksCount - 3 > 0 %}

{% set startBlocks = isValid ? entry.myMatrixField({
    limit: blocksCount - 3,
}) : null %}

Or criteria to get the last 3 blocks:

{% set endBlocks = entry.myMatrixField({
    order: 'matrixblocks.sortOrder desc',
    limit: 3,
}) %}
0
2

You can fetch all elements and slice the last 3 elements from them

{% set entriesList = entry.fieldHandle.find() %}
{% set start = entriesList|length - 3 %}
{% set end = entriesList|length %}
{% set lastThree = entriesList | slice(start, end) %}

Of course you need to make sure you have at least 3 objects your array

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.