File extensions and file icons

Hello Kirby community,

i’ve got following (part) of snippet:

$transitcodes = $data->transitcode()->split(); 
$items = page('datenbank')->children()->filterBy('template', 'document')->filter(function($item) use($transitcodes) {
  return in_array($item->documentidentifiercode(), $transitcodes);
foreach($items as $item): ?>

<a href="<?php if($file = $item->documentselect()->toFile()) {echo $file->url();} ?>"><button class="btn is-download"><i class="fas fa-arrow-down"></i></button></a>
<?= $item->title()->html() ?>

<?php endforeach ?>

the line with link (<a href… ) has documentselect()->toFile - this way it calls the file that has been selected in panel. Mostly these are word, pdf or excel files.

I’d like to add a part of snippet that recognizes file extension in order to display file icon (that i can implement via fontawesome). Is that possible?

You can get the information via $file->extension():

that’s what i’ve saw in cheatsheet too but I’ve doing something wrong that I don’t understand. I tried using this:

<?php if($item->documentselect()->extension() == 'pdf'): ?><i class="fas fa-fw fa-file-pdf"></i><?php endif; ?>

You also need to convert the field first to a file object with toFile(). And since we do not want to do that twice, you could change it to

<?php if ($file = $item->documentselect()->toFile()): ?>
<a href="<?= $file->url() ?>"><button class="btn is-download">
<?php if ($file->extension() == 'pdf'): ?>
<i class="fas fa-fw fa-file-pdf"></i>
<?php else: ?>
<i class="fas fa-arrow-down"></i>
<?php endif ?>
<?php endif ?>
1 Like

Thanks - this helped me a lot :slight_smile:

1 Like