我们可以限制for循环中的if条件吗?

Can we limit the if condition in for loop?

是否可以在for循环中只带例如12个满足我想要的条件的内容?

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

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

    {% endif %}

{% endfor %}

假设 b 中有 100 个项目。其中 60 个满足发布的 if 条件之一。然而,由于其中有 40 个不满足,例如,循环 12 次的结果是 7 个项目。 5 个循环变空。但是,我想要满足其中一个条件的总共 12 个项目。这可能吗?

注意:没有给出正确的结果如下

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

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

    {% endif %}

{% endfor %}

是的,可以这样做

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.

如有疑问请评论