1

I would like to eager load:

  1. A list of entries
  2. Within the entries loop, the first image, from the first of a block type on a matrix field.

Loading the entries like this

{% set entries = craft.entries({
  sectionId: 12,
  with: [
    'pageContent.text:text',
    ['pageContent.images:images', {
      withTransforms: [{
        width: 100,
        height: 100
      }]
    }]
  ]
}) %}

Loading the images:

Currently, I can only seem to load an image like this:

{% for block in entry.pageContent %}
  {% if block.type == 'images' %}
    {% if img is not defined %}
      {% set img = block.images[0] ?? null %}

  {% endif %}
{% endfor %}```

I cannot seems to filter the query to the matrix down like you can when getting a matrix normally, I just receive a bunch of errors, I am trying something like:

{% set img = entry.content.type('images').first.images[0] ?? null %}

Additionally, it appears I cannot use the loop to save a variable to use outside of it, I presume this is intentional and how eager loading works. If that is the case, would I even benefit from any optimisation on the query at all if it is looping on blocks I do not need? As an example, I would normally do something like

{% set img = entry.content.type('images').first.images.first ?? null %}

Following on from whether this is worth it... I also want to get a text field on this matrix (from the first of a block type again), but, in another position in the template. Does this mean I need to do another loop again to get the data specifically for another field?

Is there a better way to deal with this?

I hope that makes sense, let me know if not I'll do my best to clarify.

1

Additionally, it appears I cannot use the loop to save a variable to use outside of it

This is really a separate question. Answering it anyway: you need to give the variable some value before the loop, and then it works:

{% set img = null %} {# initial value #}

{% for block in entry.pageContent %}
  {% if block.type == 'images' %}
    {% if not img %}
      {% set img = block.images[0] ?? null %}
    {% endif %}
  {% endif %}
{% endfor %}

{# img will be the first image of first 'images' block, or null #}
| improve this answer | |
0

This article may be helpful to you: Speed up your Craft CMS Templates with Eager Loading

Basically, when you eager load the Matrix blocks, you're no longer getting an ElementCriteriaModel, rather you're getting an array pre-loaded with the Matrix blocks. That's why you can't do something like entry.pageContent.type('images').first.images

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