1

Unfortunately I'm still very new to Craft, but I have a question to which I haven't found an answer here or in the Docs or the ones I found don't seem to work in my case.

I want to output all the images for each entry in this loop and I don't understand how I get the "set image = entry.startbilder" to work that way?

I understand that ".one()" only outputs the first image but how do I change that to output all images? changing that to ".all()" results in an error.

{% for entry in craft.entries.section('projekte').all() %}  
    <a href="{{ entry.url }}">      
        {% set image = entry.startbilder.one() %}
        {% if image %}
            <img src="{{ image.getUrl('medium') }}" alt="{{ image.title }}" />
        {% endif %}
    </a>        
{% endfor %}

thanks in advance for any help!

1

You should use .all(), but that will give you an array of Assets. You can't call .getUrl() on an array, so you'd have to loop that array:

{% for entry in craft.entries.section('projekte').all() %}  
    <a href="{{ entry.url }}">      
        {% set images = entry.startbilder.all() %}

        {% if images |length %}
            {% for image in images %}
                <img src="{{ image.getUrl('medium') }}" alt="{{ image.title }}" />
            {% endfor %}
        {% endif %}
    </a>        
{% endfor %}

If you'd want to eager load the images, this is how you'd do it:

{% for entry in craft.entries.section('projekte').with(['startbilder']).all() %}  
    <a href="{{ entry.url }}">      
        {% if entry.startbilder |length %}
            {% for image in entry.startbilder %}
                <img src="{{ image.getUrl('medium') }}" alt="{{ image.title }}" />
            {% endfor %}
        {% endif %}
    </a>        
{% endfor %}
  • hi paul, thank you very much for this detailed answer. if someone has worked with expressionengine for many years before, it is sometimes difficult to adjust to the different approach of craft. I now understand the basic error I've made… and I should always use eager loading because it is much more efficient if I use lots of transformed images, right? thanks! – Matthias Feb 20 at 17:52
  • It’s always useful, when in devMode, to use {{ dump(variable) }} to see what you’re dealing with. If it’s an array, use a for loop. If it’s an object, look it up in the class reference and see what methods or attributes you can use 👍 – Paul Feb 20 at 17:56

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.