2013-04-05 46 views
5

我使用树枝并在数组中有一些数据。我使用循环访问所有这样的数据:选择树枝中的前一个项目for

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

是否有可能访问循环中的前一个项目?例如:当我在n项目,我想要访问n-1项目。

回答

9

有没有内置的方式做到这一点,但这里有一个解决方法:如果是neccessary对于第一次迭代

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

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

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

的。

+1

谢谢。此解决方案正常工作。 – repincln 2013-04-06 12:45:28

0

除了@Maerlyn的例子,这里是代码,以提供next_item(一个当前操作后)

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

我的解决办法:

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

我不得不在第一个项目去最后一个之前和最后一个项目去第一个之前做无尽的图像库。这可以这样做:

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