1

I have a section of entries and I would like to output the position of the current entry to the entry template.

I have a code that was working in Craft 3 but it broke in Craft 4 and I am struggling to fix it...

This is my old code:

{% set entryIds = craft.entries.section('movementEpisodes').orderBy('postDate asc').ids() %}
{% set position = '' %}
{% for key, value in entryIds if value == entry.id %}
        {% set position = key + 1 %}
{% endfor %}
<h1>Material for the brain #{{ position }}</h1>

I am aware that it is not possible anymore to have an 'if' inside a 'for' loop. What would be the correct way to do it in Craft 4?

I also tried another approach that didn't work but kept getting the number 1:

{% set entries = craft.entries().section('movementEpisodes').orderBy('postDate').all() %}
{% set currentPosition = 0 %}
{% for entry in entries %}
    {% if entry.id == entry.id %}
        {% set currentPosition = loop.index %}
        {% break %}
    {% endif %}
{% endfor %}
<h1>Material for the brain #{{ currentPosition }}</h1>

Any help would be highly appreciated !!

1 Answer 1

3

No need for a loop really, just use the filter filter, followed by the keys filter to do the same thing:

{% set entryIds = craft.entries.section('movementEpisodes').orderBy('postDate asc').ids() %}
<h1>Material for the brain #{{ entryIds|filter(item => item == entry.id)|keys[0] + 1 }}</h1>

Less really is more ;-)

1

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.