I am using the new image type to store images for pages and I am wondering how I would accomplish adding an alt tag to these images. Below is my blueprint.
label: Vehicle Image
and here is how I am accessing the image in the template.
<?php echo $car->picture()->toFile() ?>
Where do I place the alt tag at?
The alt tag can be attached directly to your images.
See here for more information: https://getkirby.com/docs/panel/blueprints/file-settings#file-fields
In this case you would have to modify your code a bit:
<img src="<?= $car->picture()->toFile()->url() ?>" alt="<?= $page->title() ?>">
Edit: Or use any other field for the alt tag, i.e. file meta data.
$image = $car->picture()->toFile();
<img src="<?= $image->url() ?>" alt="<?= $image->caption() ?>">
So the alt tag is working but I cannot get the image to show. Is
Have you turned on debugging? Do you get an error?
In my last example I had the $ sign missing in front of the variable … I corrected it above.
toFile()->url() is valid code.
This is the error.
PHP Fatal error: Call to a member function url() on a non-object
Does the image exist? In cases like this, it’s always safer to use an if statement before using a method on an object.
Does it work if you use
That was it. I needed to check if the file existed since some items had images and some did not.
Yeah, that is a quite common problem …
I didn’t think about that because just using the
picture->toFile alone it didn’t care if there was an image or not. Add the
url() and it has a fatal error.
It takes a while to make a habit of using if statements whenever something might break otherwise. Even if your code works for the moment, any user might e.g. delete a file at a later stage. So you are always on the safe side if you make sure an object exists.