1

If have this in a template:

{% for mainLink in section.links.limit(4).all() %}
{% endfor %}

{% for secondaryLink in section.links.offset(4).all() %}
{% endfor %}

Which I thought would show the first four in the first list and however many from 5 onwards in the secondary list. But what's happening is that the second list is limiting the output to 4 as well. Why is that?

3

When you're setting section.links.limit(4), Craft will persist that limit in subsequent calls.

This was a change introduced in Craft 3, which you can read about Changes in Craft 3 | Cloning Element Queries


You have two options to resolve your issue:

Use clone() to create a new version of the ElementCriteriaModel for each time you use section.links

{% for mainLink in clone(section.links).limit(4).all() %}
{% endfor %}

{% for secondaryLink in clone(section.links).offset(4).all() %}
{% endfor %}

Or unset the limit your limit in the second for loop

{% for mainLink in section.links.limit(4).all() %}
{% endfor %}

{% for secondaryLink in section.links.limit(null).offset(4).all() %}
{% endfor %}
3

Joshua M's answer explains why it's happening, but in terms of best practice, you'd be better off avoiding multiple roundtrips to the database by using Twig filters on a single result set. There are probably a few different ways, but here's one using slice:

{% set allLinks = section.links.all() %}

{% for link in allLinks|slice(0, 3) %}
    {# iterate through the first 4 items #}
{% endfor %}

{% for link in allLinks|slice(3) %}
    {# iterate from the 4th item to the last #}
{% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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