2013-04-05 27 views
5

Używam gałązki i mam pewne dane w tablicy. Używam pętli do dostępu do wszystkich danych takich jak ta:wybierz poprzedni element w gałązce dla pętli

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

Czy można uzyskać dostęp do poprzedniego elementu w pętli? Na przykład: kiedy jestem na pozycji n, chcę mieć dostęp do elementu n-1.

Odpowiedz

9

Nie ma wbudowanego sposób to zrobić, ale tutaj jest obejście:

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

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

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

if jest konieczne dla pierwszej iteracji.

+1

Dzięki. To rozwiązanie działa dobrze. – repincln

0

Oprócz przykład @Maerlyn jest tutaj to kod zapewnienie next_item (jednego po bieżącej)

{# 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

Proponowane rozwiązanie:

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

miałem stworzyć niekończącą się galerię zdjęć, w której przed pierwszą rzeczą idzie ostatnia i po ostatniej pozycji idzie pierwsza. Można to zrobić w ten sposób:

{% 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 %} 
Powiązane problemy