Fetching the the webp twin of an jpg or png Image

Hello there!

I m trying to create a an if clause which creates an alternative link of a jpg file to its webp twin.
It should be followed by a fallback if the twin doesn’t exist.

I tried through trail and error to get there but now I m getting a server error at a point where I thought this would work.

<?php if($project->CoverImage()->exists()): ?> 
<?php $coverImage = $project->CoverImage()->toFile() ;
        $name = $coverImage->name() ;
        $webpURLofCoverImage = $name.'.webp';
        $newWebpImage = asset($webpURLofCoverImage);      
?>
<img src="<?= $newWebpImage->url() ?>">

if this would work I could create a picture tag with two different sources and a fallback.

I m also open to get advise on another route to go to resolve that problem.

thank you very much in advance.

There is at least one issue with your code which is the if statement because it checks the wrong stuff and the endif part is missing, so should be:



<?php if ( $coverImage = $project->CoverImage()->toFile() ) :
        $name = $coverImage->name() ;
        $webpURLofCoverImage = $name.'.webp';
        $newWebpImage = asset($webpURLofCoverImage); 
?>
<img src="<?= $newWebpImage->url() ?>">
<?php endif; ?>

Background: Event if your field exists and is not empty, it doesn’t mean that the file exists, so checking for the field existence or if the field is empty is not necessary. But checking for a file object is.

Secondly, where exactly is the webp variant located? The asset helper needs the path to the file, e.g.

asset('assets/images/filename')

thank you very much for your answer and especially the background info.
the .webp twin sits in the same folder as the image: in the project folder.

If I understood correctly to create and asset means to create a file object (correct ?)
and to create it I need a relative path.

Ah, then you should not use the asset helper, because that’s for files outside the content folder.



<?php if ( $coverImage = $project->CoverImage()->toFile() ) :
        $name = $coverImage->name() ;
        $webpURLofCoverImage = $name.'.webp';
        if ( $newWebpImage = $project->image($webpURLofCoverImage) ) : ?> 

          <img src="<?= $newWebpImage->url() ?>">
        <?php endif; ?>
<?php endif; ?>
1 Like

Thank you very much pixelijn!
One for the info again and of course the solution to my problem.