1

I have an Asset field where the first image is used as a big 'feature' and then the rest are used as support further down the page.

When I add .limit(1) to the for loop for the 'feature' image it effects the for loop further down the page by also only showing 1 image.

This is my code...

{% set entries = craft.entries.section('abstractionProjects').type('abstractionProjects').all() %}
{% for projectPanels in entries %}

    Some HTML...

    {% for asset in projectPanels.projectImages.limit(1) %}
      <img src="{{ asset.url }}" alt="{{ asset.title }}">
    {% endfor %}

    Some HTML.....
    More HTML...

    {% for thumbs in projectPanels.projectImages.offset(1) %}
      <div>
          <img src="{{ thumbs.url('projectPageThumbs') }}" alt="{{ thumbs.title }}">
          <a href="{{ thumbs.url('projectPageFullSize') }}" class="gallery"></a>
      </div>
    {% endfor %}

    More HTML...

{% endfor %}

If I remove the .limit(1) from the first loop all the images are shown in both loops :/

Help appreciated

Thanks

3
  • Have you tried using projectPanels.projectImages.first() or projectPanels.projectImages[0] to access the first item.
    – a-am
    Jul 3, 2018 at 16:07
  • Thanks Aran... now I get "Impossible to access an attribute ("url") on a string variable ("3")." when trying both .first() and [0]
    – Martin
    Jul 3, 2018 at 16:11
  • 1
    Try accessing the first asset without the for loop. <img src="{{ projectPanels.projectImages[0].url }}" alt="{{ projectPanels.projectImages[0].title }}">
    – a-am
    Jul 3, 2018 at 16:54

1 Answer 1

1

Yes, this is actually the intended behaviour, and one that changed when going from Craft 2 to Craft 3. You can read more about it in the Changes in Craft 3 article in the docs. projectImages in this case which is an Asset field (I assume), returns an ElementQuery when you access it with projectPanels.projectImages. The field doesn't automatically return a new model when accessed, it returns the reference to the one and same query.

The workaround is to either reset the parameters you need to reset, like limit() in this case, or use clone as described in that article.

Ie, either something like this:

{% for asset in projectPanels.projectImages.limit(1).all() %}
   ...
{% endfor %}

{% for thumbs in projectPanels.projectImages.limit(null).offset(1).all() %}
   ...
{% endfor %}

Or,

{% for asset in clone(projectPanels.projectImages).limit(1).all() %}
   ...
{% endfor %}

{% for thumbs in clone(projectPanels.projectImages).offset(1).all() %}
   ...
{% endfor %}

Have stumbled on this quite a few times myself alreadym, it's a bit confusing. Hope this helps though. :)

0

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.