LOOP CONTEXT

HI all,

in a FOR loop with optional if condition, loop.index is incremented even if the condition fails. For example:

{% for el in elements if el.someCheck()%}
{% if not loop.first %}, {% endif %} {{el}}
{% endfor %}

If the first el check fails, skipping the cicle, VOLT will print the comma before the first printed element even if it is the really first executed cicle. I've looked around the documentation but no alternative index is provided to check the iteration position considering the condition.

Any ideas? Thanks

My guess is the loop context is built as soon as the FOR is encountered. When the loop is executed, and the condition fails, the index increments. So, if the "if" condition makes the first element be skipped, it moves on to the second element. While that second element is indeed the first one that causes the loop to execute, it is not the first time the "for" condition has been executed. Does that make sense?

While it's not as pretty, you could try referencing the index manually. Assuming "elements" is an numerically indexed array:

{% FOR index,el in elements IF el.someCheck() %}
   {% IF index != 0 %}, {% ENDIF %} {{el}}
{% ENDFOR %}