Excluding and including certain file names in a loop

Hey there,

I’m having issues excluding and including certain file names in a loop.

In the collection of files (images and videos) I have a poster image for each video. To match them i’m using the following filename structure:

video: myVideo.mp4, mySecondVideo.mp4
poster: myVideo.poster.gif, mySecondVideo.poster.gif 
[...the rest of images]

How would you exclude anything .poster from showing as image (first if) and include a matching filename for video (second if) - in case there are two or more videos with different names.

<?php foreach ($project->files() as $file): ?>
  <div>

    <?php if($file->type() == 'image'): ?>
      <img src="<?= $file->url() ?>">
    <?php endif ?>

    <?php if($file->type() == 'video'): ?>
      <video
        poster="$video_file_name.poster.gif"
      >
        <source src="<?= $file->url() ?>" type="video/mp4" />
      </video>
    <?php endif ?>

  </div>
<?php endforeach ?>
<?php foreach ($project->files()->filterBy('filename', '!*=', 'poster') as $file): ?>
  <div>

    <?php if($file->type() == 'image'): ?>
      <img src="<?= $file->url() ?>">
    <?php endif ?>

    <?php if($file->type() == 'video'): ?>
    <?php $poster = $page->file($file->name() . '.poster.gif');
      <video poster="<?= $poster?  $poster->url() : null ?>"
      >
        <source src="<?= $file->url() ?>" type="<?= $file->mime() ?>" />
      </video>
    <?php endif ?>

  </div>
<?php endforeach ?>

@texnixe This is Great, thank you!! :clinking_glasses:

@texnixe Follow up question, for some reason file reordering in panel now doesn’t affect front end. How would you approach debugging it?

This is the blueprint for files album.yml

title: Album
status:
  draft: true
  listed: true
columns:
  - width: 2/3
    sections:
      images:
        type: files
        layout: cards
        template: image
        info: "{{ file.dimensions }}"
        image:
          ratio: 5/4
          cover: true
        min: 1
        size: small
  - width: 1/3
    fields:
      headline:
        type: text
      credits:
        type: text

If you manually reorder files in the Panel, Kirby adds a sorting number to the meta data file. You have to sort your files by that number in your template then:

$files = $page->files()->sortBy('sort', 'asc');
1 Like