How to create background image for layout field?

I want to give editor ability to set background image for each layout. In blocks layout settings I have field:

bgimage:
  type: files

And in template I have:

<?php if($image = $layout->bgimage()->toFile()): ?>
  <?= $image->url() ?>
<?php endif ?>

But it prints url like this:

https: mywebsite.com media pages home 2fa432d22c-1637583129 imagetitle.jpg

Also tried other ways.

Ok, finally figured out :slight_smile: the problem is here:

style="background: url( "  <?php if($image = $layout->bgimage()->toFile()): ?>
  <?= $image->url() ?>
<?php endif ?>  " )

It works this way:

style="background: url(   <?php if($image = $layout->bgimage()->toFile()): ?>
  <?= $image->url() ?>
<?php endif ?>  )

Needed to remove quotes in url( " " )

If I were you, I would put extract the if statement out of the style settings to make your code more readable:

<?php $url = ($image = $layout->bgimage()->toFile()) ? $image->url() : null; ?>

Then

style="background: url( <?= $url ?> )"