1

From what I understand it is wise to always eager load assets, I used it successfully in other cases, but here it results in a more queries, not fewer.

I am trying to eager load an asset in a matrix field from the current page entry and it seems I missed something 😓

Here are the 2 versions of my code:

Without eager loading

{% for block in entry.articleBody %}
    {% switch block.type %}
        {% case 'text' %}
            {{ block.text }}

        {% case 'img' %}
            {% set img = block.img.one() %}
            
            {% if block.position == 'full' %}
                {% set url = img.getUrl('articleFull') %}
                {% set url2x = img.getUrl('articleFull2x') %}
            {% else %}
                {% set url = img.getUrl('articleHalf') %}
                {% set url2x = img.getUrl('articleHalf2x') %}
            {% endif %}
            <img src="{{  url ?? img.url }}"
                srcset="{{ url }} 1x, {{ url2x }} 2x"
            alt="">
    {% endswitch %}
{% endfor %}

With what I understand should be eager loading

{% set articleBlocks = entry.articleBody
    .with([
        ['blockType:img', {
            withTransforms: ['articleHalf', 'articleHalf2x', 'articleFull', 'articleFull2x']
        }]
    ])
    .all() %}
{% for block in articleBlocks %}
    {% switch block.type %}
        {% case 'text' %}
            {{ block.text }}

        {% case 'img' %}
            {% set img = block.img[0] ?? null %}

            {% if block.position == 'full' %}
                {% set url = img.getUrl('articleFull') %}
                {% set url2x = img.getUrl('articleFull2x') %}
            {% else %}
                {% set url = img.getUrl('articleHalf') %}
                {% set url2x = img.getUrl('articleHalf2x') %}
            {% endif %}
            <img src="{{  url ?? img.url }}"
                srcset="{{ url }} 1x, {{ url2x }} 2x"
            alt="">
    {% endswitch %}
{% endfor %}

1 Answer 1

1

Hum,

The problem was very simple. I didn't understand what the query was about and it showed.

I used blockType:img in my query thinking blockType was a keyword instead of using the actual block slug witch in my case is image.

Once fixed, the number of queries did get under the non eager loaded version 🥳

Here is the relevant part of the fixed code:

{% set articleBlocks = entry.articleBody
    .with([
        ['image:img', {
            withTransforms: ['articleHalf', 'articleHalf2x', 'articleFull', 'articleFull2x']
        }]
    ])
    .all() 
%}

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.