How do I output the first image in a group of images?

On a Single page or within a Channel or Structure craft.entries loop, you can access all of your fields using the entry variable. You can access the first image in an Assets field in the following way:

{% set image = entry.assetFieldHandle.first() %}

<img src="{{ image.getUrl() }}" width="{{ image.getWidth() }}" height="{{ image.getHeight() }}">

Note: You must interact with your Asset fields as if they are arrays, even if you just have a single image.

If we have an image transform setup in our settings, we can pass that transform to each of our asset methods getUrl(), getWidth(), and getHeight().

{% set image = entry.assetFieldHandle.first() %}

<img src="{{ image.getUrl('transformHandle') }}" width="{{ image.getWidth('transformHandle') }}" height="{{ image.getHeight('transformHandle') }}">

If we want to confirm that we have an image before we try to output the image, we can test the Asset field using the |length filter.

{% if entry.assetFieldHandle | length %}

    {% set image = entry.assetFieldHandle.first() %}

    <img src="{{ image.getUrl() }}" width="{{ image.getWidth() }}" height="{{ image.getHeight() }}">

{% endif %}

Since our Assets field is an array, we can also try to access our images as if we were working with an array. Since an array starts with number zero, we can do the following:

{% set image = entry.assetFieldHandle[0] %}

<img src="{{ image.getUrl() }}" width="{{ image.getWidth() }}" height="{{ image.getHeight() }}">

Don't miss any Craft tips, tricks, and community updates