What I already can do is this:
{% for _item in objects %}
{{ _item.id }}
{% endfor %}
or this:
{% for i in 0..objects|length-1 %}
{{ objects[i].id }}
{% endfor %}
To loop though the whole array.
What I want to do is:
Kinda like this - depending on which is smaller (imagine there are only 5 items):
{% for i in 0.. (10 OR objects|length-1) %}
{{ objects[i].id }}
{% endfor %}
What's the easiest/shortest way of writing this?
EDIT
Of course, I could test it in my controller and than pass the result as a variable to the template, but isn't there an easier way?
You're looking for the slice filter.
Posting for anyone who may need this in the future.
I accomplished this with the following slice method to get half of the array and then the other half. I needed this to set a class for only the first half of an array, no matter the number (in my case nav sub-items). Remember to update Array
as needed
{% set half_first = Array|slice(0, Array|length / 2) %}
{% set half_second = Array|slice(Array|length / 2) %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With