Problem with scope in macro I've written a short macro to get the first image inside a matrix field.

{% macro firstImage(entry) %}

    {% set image = 'hello' %}

    {% if entry.sliderMatrix.total() %}
        {% set block = entry.sliderMatrix|first %}
        {% set image = block.image|first %}
    {% endif %}

    {{ image.url }}

{% endmacro %}


The code throws this error: Impossible to access an attribute ("url") on a string variable ("hello")

{{ image.url }} inside the if statement works fine.

{{ image }} outside the if statement works too.

Is there anything I don't know or it's even a bug?
Hard to say for sure, but here's what I suspect... You may have multiple instances of firstImage being called from your main template.

For some of those instances, entry.sliderMatrix.total is greater than zero. For other instances, entry.sliderMatrix.total is equal to zero. And of course, when entry.sliderMatrix.total is equal to zero, your if statement will be bypassed.

Realistically, you shouldn't have the image.url call outside of your if statement. Because any time the if statement evaluates to false, then the image variable won't be what you want it to be. In fact, you'll get that exact error, since image will still be set to a string.