Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select previous item in twig for loop

Tags:

for-loop

twig

I use twig and have some data in array. I use for loop to access all data like this:

{% for item in data %}
    Value : {{ item }}
{% endfor %}

Is it possible to access previous item in loop? For example: when I'm on n item, I want to have access to n-1 item.

like image 909
repincln Avatar asked Apr 05 '13 17:04

repincln


2 Answers

There's no built-in way to do that, but here's a workaround:

{% set previous = false %}
{% for item in data %}
    Value : {{ item }}

    {% if previous %}
        {# use it #}
    {% endif %}

    {% set previous = item %}
{% endfor %}

The if is neccessary for the first iteration.

like image 122
Maerlyn Avatar answered Nov 15 '22 11:11

Maerlyn


In addition to @Maerlyn 's example, here is code to provide for next_item (the one after current one)

{# this template assumes that you use 'items' array 
and each element is called 'item' and you will get 
'previous_item' and 'next_item' variables, which may be NULL if not availble #}


{% set previous_item = null %}
{%if items|length > 1 %}
    {% set next_item = items[1] %}
{%else%}
    {% set next_item = null %}
{%endif%}

{%for item in items %}
    Item: {{ item }}

    {% if previous_item is not null %}
           Use previous item here: {{ previous_item }}    
    {%endif%}


    {%if next_item is not null %}
          Use next item here: {{ next_item }}    
    {%endif%}


    {# ------ code to udpate next_item and previous_item  elements #}
    {%set previous_item = item %}
    {%if loop.revindex <= 2 %}
       {% set next_item = null %}
    {%else%}
        {% set next_item = items[loop.index0+2] %}
    {%endif%}
{%endfor%}
like image 26
Dimitry K Avatar answered Nov 15 '22 13:11

Dimitry K