Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit twig loop

Tags:

loops

php

twig

How can I make the following iteration list 5 items max only?

<ul class="list-unstyled childs_2">  
{% set wi = 0 %}
{% for wi in wi..category.children[i]['children_level2']|length %}
<li><a href="{{ category.children[i]['children_level2'][wi]['href'] }}">
{{ category.children[i]['children_level2'][wi]['name'] }}</a>
</li>  
{% endfor %}        
</ul>
like image 317
Joe Avatar asked Mar 16 '26 06:03

Joe


1 Answers

I think iterating over a subset may work for what you're doing here. With that approach, the wi variable shouldn't be necessary, unless you're using it for something else as well.

<ul class="list-unstyled childs_2">  
{% for child in category.children[i]['children_level2']|slice(0, 5) %}
    <li>
        <a href="{{ child['href'] }}">{{ child['name'] }}</a>
    </li>  
{% endfor %}        
</ul>
like image 120
Don't Panic Avatar answered Mar 18 '26 21:03

Don't Panic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!