2013-04-05 2 views
5

Uso il ramoscello e alcuni dati nell'array. Io uso per il ciclo di accedere a tutti i dati in questo modo:selezionare l'elemento precedente nel ciclo per il ciclo

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

E 'possibile accedere all'elemento precedente nel ciclo? Ad esempio: quando sono su n elemento, voglio avere accesso a n-1 articolo.

risposta

9

Non c'è modo integrato per farlo, ma ecco una soluzione:

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

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

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

Il caso è neccessary per la prima iterazione.

+1

Grazie. Questa soluzione funziona bene. – repincln

0

Oltre all'esempio @Maerlyn s', qui è il codice di prevedere next_item (quella dopo quella corrente)

{# 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%} 
0

La mia soluzione:

{% for item in items %} 

    <p>item itself: {{ item }}</p> 

    {% if loop.length > 1 %} 
    {% if loop.first == false %} 
     {% set previous_item = items[loop.index0 - 1] %} 
     <p>previous item: {{ previous_item }}</p> 
    {% endif %} 

    {% if loop.last == false %} 
     {% set next_item = items[loop.index0 + 1] %} 
     <p>next item: {{ next_item }}</p> 
    {% endif %} 

    {% else %} 

    <p>There is only one item.</p> 

    {% endif %} 
{% endfor %} 

ho dovuto crea una galleria di immagini senza fine dove prima il primo oggetto va per ultimo e dopo l'ultimo oggetto va primo. Si potrebbe fare in questo modo:

{% for item in items %} 

    <p>item itself: {{ item }}</p> 

    {% if loop.length > 1 %} 
    {% if loop.first %} 
     {% set previous_item = items[loop.length - 1] %} 
    {% else %} 
     {% set previous_item = items[loop.index0 - 1] %} 
    {% endif %} 

    {% if loop.last %} 
     {% set next_item = items[0] %} 
    {% else %} 
     {% set next_item = items[loop.index0 + 1] %} 
    {% endif %} 

    <p>previous item: {{ previous_item }}</p> 
    <p>next item: {{ next_item }}</p> 

    {% else %} 

    <p>There is only one item.</p> 

    {% endif %} 
{% endfor %}