4

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

2 Answers 2

8

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 %}
1
  • 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 Commented Jul 29, 2014 at 5:35
2

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.

1
  • 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
    Commented Aug 13, 2014 at 20:58

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.