0

How we can use break statement in twig template?

Here is my php code

<?php 
     $i=0;
     foreach($products as $product){
       echo $product['name'];
       $i++;
       if($i==5){
         break;
       }
     }
?>
Cœur
  • 37,241
  • 25
  • 195
  • 267
Meldin Xavier
  • 197
  • 4
  • 14

2 Answers2

2

You either limit the array size inside you controller, which is the best method, or you could use the filter slice

{% for product in products|slice(0,5) %}
   {{ product.name }}
{% endfor %}
DarkBee
  • 16,592
  • 6
  • 46
  • 58
1

Twig doesn't include a break statement. According to the official manual, the equivalent instruction is the for + if condition. Check the documentation here for some alternative.

or

here

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59