My image->url() function returns weird path

HI everyone

i did this function to include the page header image by using the blueprint: coverImage is my image.

title: Content

files: true

fields:
  title:
    label: Page Heading
    type: text

  title2:
    label: Heading 4 (h4)
    type:  text

  text:
    label: Texteingabe
    text:  text

  coverImage:
      label: Cover Image
      type: image

this is the function in php, but it returns this path: “http://localhost/project-name/n00277490.jpg” when i use coverImage->url() also if i use $page->coverImage()->url()

<?php
  $headerImage = '';
    if($page->hasImages()) {
      $coverImage = $page->coverImage();
        print_r('<pre>');
        var_dump($coverImage()->url());
        print_r('</pre>');
      $headerImage.= '<header class="header" style="background-image: url('. $coverImage->url(). ')">';
    } else {
      $headerImage.= '<header class="header" style="background-image: url(\'assets/files/rack.jpg\')">';
    }
    echo $headerImage; ?>
    <?= snippet('menu') ?>

Maybe you can give me a hint what i’am doing wrong and how to get the right image url()

i used this as reference: https://getkirby.com/docs/cookbook/handling-images-in-kirby#accessing-images-in-templates

best Pascal

You have to get a file/image object first, using the foFile() method is one option:

<?php
$coverImage = $page->coverImage()->toFile();
// it is important to check if the image exists, otherwise the `url()` method would throw an error
if($coverImage) {
   $url =  $coverImage->url();
} else {
  $url = url('assets/files/rack.jpg');
}
?>
<header class="header" style="background-image: url(<?= $url ?>)">

Alternative:

<?php
if($coverImage = $page->image($page->coverImage())) {
 $url =  $coverImage->url();
}
else {
  $url = url('assets/files/rack.jpg');
}
?>
<header class="header" style="background-image: url(<?= $url ?>)">
1 Like

Super cool, thank you @texnixe!

Works now fine with ->toFile()