1

On my site I have some entries with images. In the entry template I paginate the images like so:

{% paginate entry.images.limit(1) as images %}

My homepage is a single random entry and I want to paginate it as well. The Problem is, paginate expects an elementcriteriamodel, not an array. So this doesn't work:

{%
set project = craft.entries()
    .section('projects')
    .orderBy('RAND()')
    .with([
        ['images', { withTransforms: 'width' }],
        ['category']
    ])
    .one() %}
{% paginate project.images.limit(1) as images %}

I tried this, but that somehow doesn't work in Craft 3.

{% set queryParams = {
    with:[['images', { withTransforms: 'width' }],['category']]
}
%}

{%
set project = craft.entries(queryParams)
    .section('projects')
    .orderBy('RAND()')
    .one() %}

{% paginate project.images.limit(1) as images %}

Any solutions?

5

project.images is an array because you are eager-loading the images.

Since you’re only loading one project entry, you’re not actually gaining anything by eager-loading the images (or category), though. In fact, you’re actually slowing things down a bit. Eager-loading does come with a little bit of overhead, so you should only use it when you’ve got an “n+1” problem, as described on the Eager-Loading Entries page.

So to get this working, just remove the with param.

{% set project = craft.entries()
    .section('projects')
    .orderBy('RAND()')
    .one() %}

{% paginate project.images.limit(1) as images %}

Note that this will also affect how you access your category, as project.category will go from an eager-loaded array, back to a category query.

| improve this answer | |

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.