URL path not showing for image

Hi,

I cant figure out why the full path of the image URL is not showing on the frontend of the website. Below is the PHP snippet:

<?php foreach ($page->children()->listed() as $work): ?>
          <li>
            <a href="<?= $work->url() ?>">
              <figure>
                  <img src="<?= $work->cover()->url() ?>">
                <figcaption class="project-name">
                  <?= $work->title() ?>
                </figcaption>
              </figure>
            </a>
          </li>
        <?php endforeach ?>

Yet on the frontend the img tag is:

<img src="- image-1.png">

YAML:

- width: 1/3
          sections:
            images:
              type: fields
              fields:
                cover:
                  label: Main Image
                  type: files
                  template: image-template

Please can somebody point me in the right direction? Thank you

The value of the cover field first has to be turned into a file/files object before you can retrieve its URL:

(toFile() if the field contains a single file; toFiles() if multiple, in which case you may e.g. want to use->toFiles()->first() to return the first of many)

Edit: Two more things to observe, just mentioning for completeness

  1. Before working with a file object, always check that a file exists:
<?php if ($cover = $page->cover()->toFiles()->first()) : ?>
<img src="<?= $cover->url() ?>" alt="">
<?php endif ?>
  1. Omitting the alt attribute in your img tag will make screen reader programs read out the entire URL, so for accessibility reasons this should be either empty (if the image content is not relevant) or a good description of what is depicted in the image.
1 Like