Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

I've got a Assets field which is limited to 1 asset inside a Matrix field. Is there a better way to fetch the image without using a forloop?

At the minute I've got:

{% for image in block.backgroundImage %}
    {{ image.getUrl() }}
{% endfor %}

But it just doesn't seem right using a forloop when I know there is only one image.

Thanks

share|improve this question

2 Answers 2

up vote 7 down vote accepted

You can call the first() function to just get the first image:

{% set image = block.backgroundImage.first() %}
{{ image.getUrl() }}

But this will fail if there is no image. So to be safe, you need:

{% set image = block.backgroundImage.first() %}
{% if image %}
    {{ image.getUrl() }}
{% endif %}
share|improve this answer
3  
You could always use an inline conditional to get it down to one line, just for fun...: {% block.backgroundImage | length ? block.backgroundImage.first().getUrl() : '' %} :D –  joshangell Jul 29 at 5:35

Looking for the exact same answer I came across this question and would argue that joshangell's answer is the best if trying to simplify down from a for loop to one line of code. The only issue is that the answer uses incorrect wrapping tags for an inline if statement. So I submit this as the best answer for simplification and correct syntax:

{{ block.backgroundImage | length ? block.backgroundImage.first().getUrl() : '' }}

Just used it in my own project and it worked like a charm.

share|improve this answer
    
Another idea to get it down to one line would be to wrap it into a macro. Then you can easily add things like retina versions or common CSS classes to the HTML output and still have a clean template code in one line. –  carlcs Aug 13 at 20:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.