Ad

Can We Limit The If Condition In For Loop?

- 1 answer

Can I bring for example only 12 contents in a for loop that satisfy the condition I want?

{% for i, a in b %}
    
    {% if a.c[0].d == x %}

    {% elseif a.c[1].d == y %}

    {% endif %}

{% endfor %}

Let's say there are 100 items in b. 60 of them meet one of the if conditions posted. However, as 40 of them do not meet, for example, 7 items come as a result of for loops that rotate 12 times. 5 loops turn empty. However, I want a total of 12 items that meet one of these conditions. Is this possible?

Note: it does not give the right result as follows

{% for i, a in b|slice(0, 12) %}
    
    {% if a.c[0].d == x %}

    {% elseif a.c[1].d == y %}

    {% endif %}

{% endfor %}
Ad

Answer

yes it's possible to do that

Example

{% set items = [2,4,6,8,16,18,20,22,3,5,7,15,33,13, 25, 24, 28] %}
<h1> total records : {{items|length}} </h1>

{% set metWithConditionA  = [] %}
{% set metWithConditionB  = [] %}
{% set metWithConditionAB = [] %}

{% for item in items %}    
    {% if item % 2 == 0 %}
        {% set metWithConditionA = metWithConditionA|merge([item]) %}
        {% set metWithConditionAB = metWithConditionAB|merge([item]) %}        
    {% elseif item % 2 == 1 and item > 10%}
        {% set metWithConditionB = metWithConditionB|merge([item]) %}
        {% set metWithConditionAB = metWithConditionAB|merge([item]) %}        
    {% endif %}
{% endfor %}


<h1>metWithConditionA : {{metWithConditionA|length}}</h1>
{% for item in metWithConditionA %}    
    {{item}}
{% endfor %}

<hr/>
<h1>metWithConditionB : {{metWithConditionB|length}}</h1>
{% for item in metWithConditionB %}    
    {{item}}
{% endfor %}

<hr/>
<h1>metWithConditionAB : {{metWithConditionAB|length}}</h1>
{% for item in metWithConditionAB %}    
    {{item}}
{% endfor %}

<hr/>
<h1>12 items</h1>
{% for item in metWithConditionAB|slice(0, 12) %}    
    {{item}}
{% endfor %}

Output , Now You can take 12 items from metWithConditionAB and loop through them.

output-twig

if any doubts please comment.

Ad
source: stackoverflow.com
Ad