Select the previous item in the curl chain.

I use a branch and have some data in the array. I use for loop to access all data as follows:

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

Is it possible to access the previous item in a loop? For example: when I am in element n , I want to access element n-1 .

+5
source share
3 answers

There is no built-in way to do this, but here is a workaround:

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

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

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

If the first iteration is necessary,

+9
source

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

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

My decision:

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

I had to create an endless gallery of images where the last element comes before the first element, and the first after the last element. This can be done as follows:

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

All Articles