Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig - loop through part of an array

Tags:

twig

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:

  • loop through a part of an array
  • if the end of the array is reached: stop (instead of throwing an exception)

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?

like image 728
insertusernamehere Avatar asked Oct 07 '22 07:10

insertusernamehere


2 Answers

You're looking for the slice filter.

like image 69
Maerlyn Avatar answered Oct 12 '22 11:10

Maerlyn


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) %}
like image 44
wouch Avatar answered Oct 12 '22 10:10

wouch