insertusernamehere
insertusernamehere

Reputation: 23580

Twig - loop through part of an array

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?

Upvotes: 5

Views: 11162

Answers (2)

Maerlyn
Maerlyn

Reputation: 34107

You're looking for the slice filter.

Upvotes: 4

wouch
wouch

Reputation: 1241

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) %}

Upvotes: 2

Related Questions