Display specific image from field

Hello, I’ve been taking a look at documentation and examples, and even when my intuiton says this should be simple, I cannot solve it: I have an image field in my blueprint that allows 2 files, and I want to retrieve either the first or second image, depending on the template.

The blueprint is like this:

  featured:
    label: Featured image
    type: files
    layout: cards
    max: 2

And then in the template it works like in the documentation example:

<?php if($file = $page->file()): ?>
<?= $file->filename() ?>
<?php endif ?>

This works, but for only one file. The other example in the docs is for ALL of the images. How coul I get only the first, or the second uploaded image, dependign on the case?

Besides this, I see all files are being upload to the page’s root folder. Is there any way to define a separate folder (e.g. img) inside the page’s one, so I can have images separated from the page’s txt file?

Thanks for your tips, and have a great weekend.

The problem with your code is that you are not fetching the file stored in the field but from the file system.

With

$featuredImages = $page->featured()->toFiles();

you can fetch the files selected in the field. The rest depends on the logic you want to apply here.

Depending on the page template?

Hi! Yes, for example all the main sections will have 2 featured images.

This one example from one of section’s txt:

----

Featured:

- featured_manuales.svg
- featured_manuales_back.svg

On the header of the section itself I would like to show the image number 1, and then on the homepage, when including access to that section; I’d like to use featured image #2.

The problem I see here is that you do not require any images, so fetching the first or the second might not give you a result.

1st image

$featuredImages = $page->featured()->toFiles();
if ( $firstImage = $featuredImages->first()) {
  echo $firstImage->url();
}

2nd image

$featuredImages = $page->featured()->toFiles();
if ( $secondImage = $featuredImages->nth(2)) {
  echo $secondImage->url();
}

I would set min: 2 to make this work in all cases. You would still need the if statements in case images get deleted but at least you would make sure to have 2 images.

Perfect, thanks! I’ll try to learn more about nth, I was trying with first and last, and count, but didn’t make it work.