Alt tag - images

Could someone explain me how should I add alt tag to images, if I use such approach (below) to get images:

<?= $page->images()->find($page->headerImage())?>

The empty alt tag is visible in rendered HTML code (for example in developer tool in Chrome browser), but I don’t know how to add alternative text, so it could be shown in rendered HTML.

<?php if ($headerImage = $page->headerImage()): ?>
    <img src="<?= $headerImage->toFile() ?>" alt="<?= $headerImage->caption() ?>">
<?php endif ?>

See: Adding metadata files for images within the panel

Make sure that you really have an image first:

<?php if ($headerImage = $page->headerImage()->toFile()): ?>
    <img src="<?= $headerImage->url() ?>" alt="<?= $headerImage->caption() ?>">
<?php endif ?>

Caption here assumes that you have added meta data to your file. See

Whether or not you should add information in the alt attribute depends on the function of the image, though. The alt attribute should be empty for images that just have a decorative function and should be ignored by assistive technology.

If I remember correctly, the thumbnail method has the possibility to add html attributes to the options array as well and it uses the html()-method.
So this should work as well:

$headerImage = $page->headerImage()->toFile();
echo $headerImage->html(array("alt"=>"beautiful header image"))


Please don’t call a method without checking if you really have an image:

$headerImage = $page->headerImage()->toFile();
  echo $headerImage->html(array("alt"=>"beautiful header image"));

Because if the field is empty or contains a filename without a matching file, PHP will throw an error.

Thanks @texnixe for help! it works :slight_smile: