1

How do I split a list of 10 entries into two parts - one part with 4 entries, followed by an image section, and then the second part with 6 entries.

Thanks for your help. markus

2 Answers 2

2

You can split an array using the slice filter. This is useful if you need the two parts in separate places, this way you don't have to iterate through the entire array both times. Slice accepts two arguments, an offset and a length, and returns a new array with the specified number of items starting at the offset.

{% set chunk_1 = array|slice(0, 4) %}
{% set chunk_2 = array|slice(4, 6) %}
2
  • Thanks Moritz. Do you think that will load faster and with less server resources than loop.index? Commented Dec 17, 2021 at 10:00
  • @MarkusBusch Depends on how you're using the array elements in your template. But honestly, it doesn't matter. With ten array elements, you're talking about miliseconds. Use whichever version is easier to understand and modify in the context of your templates.
    – MoritzLost
    Commented Dec 17, 2021 at 10:14
0

You can use Twig's loop.index variable to find out where you are within a for loop.

i.e.

{% for entry in entries %}

    [...code to show entry...]

    {% if loop.index == 4 %}
        [...code to show image...]
    {% endif %}

{% endfor %}
1
  • Works like a charm. Thank you & greetings from Switzerland! Commented Dec 17, 2021 at 9:56

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.