限界を設定するオフセット?


1

これがテンプレートにある場合:

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

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

最初のリストの最初の4つを表示すると思いましたが、2番目のリストには5つ以上の多くが表示されます。しかし、何が起こっているのかというと、2番目のリストでは出力も4に制限されています。なぜですか?

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