0

I've tried to apply eager loading per Craft's docs, but it doesn't seem to work. When I do this, will I have access to all the entry fields? If not, do I have to include all the fields I want in the with attribute?

{% for entry in craft.entries.section('news').with['image'] %}
  {% set image = entry.image[0] ?? null %}
  {% if image %}
    <img src="{{ image.url }}">
  {% endif %}
  {{ entry.title }}
{% endfor %}

When I tried it, the code barfed when trying to output {{ entry.title }}.

  • 3
    Would probably be helpful to replace the word barfed with the actual error message. – Ben Parizek Mar 5 '17 at 15:46
1

there is no .with() method for the ElementCriteriaModel nor is it supported by craft.entries as a chainable method, meaning that it can't be chained to craft.entries query like that:

{% for entry in craft.entries.section('news').with['image'] %}

Especially as an array (hint: you were probably intending to use .with(['image']) instead of .with['image'].

The correct syntax for eager loading elements is:

{% set entries = craft.entries({
    section: 'news',
    with: ['image']
}) %}

or in your case it can be:

{% for entry in craft.entries({ section: 'news', with:['image'] }) %}
  {% set image = entry.image[0] ?? null %}
  {% if image %}
    <img src="{{ image.url }}">
  {% endif %}
  {{ entry.title }}
{% endfor %}

I remember also being frustrated by eager loading in craft (for some reason I also had problems using it at first), but then it turned to be quite useful. It's especially powerful if you'd like to show more then one image per entry, e.g.:

{% for i in entry.image %}
    <img src="{{ i.url }}" alt="">
{% endfor %}

Take care

|improve this answer|||||
  • 2
    This answer is mostly correct, but I confirmed with @bradbell that .with should indeed work as a chained method. The syntax is .with(['image'] or if wanting to eager load multiple things, then .with(['image1','image2']) – Jeremy Daalder Mar 11 '17 at 1:10
  • @JeremyDaalder oh nice, couldn't spot that in the official docs though… – Łukasz Mazurek Mar 24 '17 at 10:21
  • That's why I checked with Brad ;) - might be worth editing that bit off the top above. – Jeremy Daalder Mar 24 '17 at 22:41
2

The original answer is good, but as noted, somewhat incorrect, at least concerning a chainable .with() method.

Here's my attempt to explain things: Speed up your Craft CMS Templates with Eager Loading

|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.