5

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?

2 Answers 2

4

You're looking for the slice filter.

Sign up to request clarification or add additional context in comments.

1 Comment

Would you be able to add an example in addition to just a link
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.