Empty image field breaks the page

Hi there,
I added a type:image field to my blueprint and I call it in the template like this:
<figure><img src="<?php echo $page->image($page->screenshot())->url() ?>" alt="<?php echo $page->screenshotalt() ?>" /></figure>

Problem is, when the field is empty (no image yet), the layout breaks, no preview is possible for editors. Everything below the image is hidden/not rendered. But I would like to make it possible for editors to preview the layout without that image uploaded.

Thanks in advance.
Disclaimer: I am not at all a php master.

You can first check if there’s a image at all , like this

<?php if($page->image($page->screenshot())): ?>
  Your code :)
<?php endif ?>

In your situation (when there’s no image), it’s still trying to find it and display it, but it can’t so it throws an error, blocking the rendering of the rest of the page.

It works :heart_eyes: Thanks

1 Like

You can even check the image and set a variable at the same time. That way you don’t have to write it again.

<?php if($image = $page->image($page->screenshot())): ?>
    <img src="<?php echo $image->url() ?>" alt="<?php echo $page->screenshotalt() ?>" />
<?php endif ?>