Image file field correct way

Hello, everyone, great to be here.

Having some doubts about the correct way to deal with File Field, restricted to images.

  1. In my header snippet, I did this
<?php if($image = $site->favicon()->isNotEmpty()): ?>
      <link rel="apple-touch-icon" sizes="180x180" href="<?= $site->favicon()->toFile()->crop(180)->url() ?>">
      <link rel="icon" type="image/png" href="<?= $site->favicon()->toFile()->crop(32)->url() ?>" sizes="32x32">
      <link rel="icon" type="image/png" href="<?= $site->favicon()->toFile()->crop(16)->url() ?>" sizes="16x16">
      <meta name="msapplication-TileImage" content="<?= $site->favicon()->toFile()->crop(150)->url() ?>" />
      <?php endif ?>

Is that the right/best way to do it?

  1. In my site.yml I made this
favicon:
                label: Favicon
                type:  files
                help: Must be PNG file, square, max 512px height. 
                accept:
                  mime: image/png
                  maxheight: 512
                multiple: false

The goal was to restrict file type to .png but it for sure doesn’t work. I am missing some logic with this.

Please help :slight_smile:

There is no accept option for the files field. But you can use a query to limit the files shown to images.

 query: page.images

Or if you want to limit to png_

 query: page.images.filterBy('extension', 'png');

As regards the header, it’s not a good idea to call crop without checking for the image first.

I suggest the following:

<?php if($image = $site->favicon()->toFile()): ?>
      <link rel="apple-touch-icon" sizes="180x180" href="<?= $file->crop(180)->url() ?>">
      <link rel="icon" type="image/png" href="<?= $file->crop(32)->url() ?>" sizes="32x32">
      <link rel="icon" type="image/png" href="<?= $file->crop(16)->url() ?>" sizes="16x16">
      <meta name="msapplication-TileImage" content="<?= $file->crop(150)->url() ?>" />
<?php endif ?>
1 Like

Regarding the snippet, you can check if the field has a valid reference to file in the if statement and then just use the variable you are assigning it to:

<?php if($image = $site->favicon()->toFile()): ?>
    <link rel="apple-touch-icon" sizes="180x180" href="<?= $image->crop(180)->url() ?>">
    <link rel="icon" type="image/png" href="<?= $image->crop(32)->url() ?>" sizes="32x32">
    <link rel="icon" type="image/png" href="<?= $image->crop(16)->url() ?>" sizes="16x16">
    <meta name="msapplication-TileImage" content="<?= $image->crop(150)->url() ?>" />
<?php endif ?>
2 Likes
1 Like

Thank you very much.
That’s just what I was looking for. :slight_smile:

Thank you, you are right.

Oh, and welcome to the forum, of course :slightly_smiling_face:

1 Like

Just one note, for someone reading this

In site options is

query: site.images