我使用樹枝並在數組中有一些數據。我使用循環訪問所有這樣的數據:選擇樹枝中的前一個項目for
{% for item in data %}
Value : {{ item }}
{% endfor %}
是否有可能訪問循環中的前一個項目?例如:當我在n項目,我想要訪問n-1項目。
我使用樹枝並在數組中有一些數據。我使用循環訪問所有這樣的數據:選擇樹枝中的前一個項目for
{% for item in data %}
Value : {{ item }}
{% endfor %}
是否有可能訪問循環中的前一個項目?例如:當我在n項目,我想要訪問n-1項目。
有沒有內置的方式做到這一點,但這裏有一個解決方法:如果是neccessary對於第一次迭代
{% set previous = false %}
{% for item in data %}
Value : {{ item }}
{% if previous %}
{# use it #}
{% endif %}
{% set previous = item %}
{% endfor %}
的。
除了@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%}
我的解決辦法:
{% 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 %}
謝謝。此解決方案正常工作。 – repincln 2013-04-06 12:45:28