Search code examples
twigopencartopencart-3

Increase loop index in twig


Below is my code. I want to increase J loop index in between inner loop so I have incremented J variable but it is not working.

`{% for j in 0..(products|length-1) %}
{% for f in 0..(rows-1) %}
{% set j = j + 1 %}
{% endfor %}
{% endfor %}`

Is there any other way to increase loop index?


Solution

  • Its not possible to alter the loop indeces of twig due to the fact of how the loops are compiled

    {% for i in 1..5 %} for example gets compiled as

    $context['_seq'] = twig_ensure_traversable(range(1, 5));
    foreach ($context['_seq'] as $context["_key"] => $context["i"]) {
        //..
    }
    

    I do have another aproach for you to solve this with twig

    {% set rows = 2 %}
    {% set items = ((products|length) / rows) | round %}
    
    {% for product in products %}
        {% if loop.index0 % items == 0 %}
    <div class="row">
        {% endif %}
        <div class="product">
            {{ product }}
        </div>
        {% if loop.index % items == 0 or loop.last %}
    </div>
        {% endif %}
    {% endfor %}