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

carlcs
  • 36,220
  • 5
  • 62
  • 139
Keiron Lowe
  • 225
  • 1
  • 5

2 Answers2

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 %}
Brandon Kelly
  • 34,307
  • 2
  • 71
  • 137
Marion Newlevant
  • 12,047
  • 22
  • 55
  • 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 – Josh Angell Jul 29 '14 at 05: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.

Sean
  • 21
  • 2
  • 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