Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.


share|improve this question
up vote 8 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
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 – Josh Angell Jul 29 '14 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 '14 at 20:58

Your Answer


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.