Pulcino Pio
Pulcino Pio

Reputation: 83

using condition in loop on twig cycle

I want to stop the cycle if the loop is 3.
If my array has 5 records, I need to show only 3 records

{% for image in post.images %}
   {% if loop.index < '3' %}
      {{ loop.index}}
   {% endif %}
{% endfor %}

so I want show only 3 loop

1  
2  
3  

Upvotes: 0

Views: 1580

Answers (2)

Mark
Mark

Reputation: 1754

You can combine for and if statements in twig. Something like the below will work but I'm guessing it wouldn't actually be the loop index that you would ultimately be printing out?

{% for image in post.images if loop.index <= 3 %}
    {{ loop.index }}
{% endfor %}

Upvotes: 0

Pulcino Pio
Pulcino Pio

Reputation: 83

{% for image in post.images|slice(0, 3) %}

solved

Upvotes: 2

Related Questions