0

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 %}
Ersin
  • 39
  • 6
  • what is the issue with the above code, can you share more details – Hardik Satasiya Mar 16 '21 at 05:15
  • @HardikSatasiya 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? – Ersin Mar 16 '21 at 06:29
  • Does this answer your question? [How can I use break or continue within for loop in Twig template?](https://stackoverflow.com/questions/21672796/how-can-i-use-break-or-continue-within-for-loop-in-twig-template) – DarkBee Mar 16 '21 at 07:27

1 Answers1

1

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.

Hardik Satasiya
  • 9,547
  • 3
  • 22
  • 40