How do i show images and videos in a project page?

I’m editing the kirby starter template for single project (project.php) and i cant quite figure how to loop through the content and show either image or video.

Here’s my code so far:

 <!-- image-->
  <?php
  foreach($page->images()->sortBy('sort', 'asc') as $image): ?>
    <figure>
      <img src="<?= $image->url() ?>" alt="<?= $page->title()->html() ?>" />
    </figure>
  <?php endforeach ?>

 <!-- video-->
  <?php
  foreach($page->videos()->sortBy('sort', 'asc') as $video): ?>
    <figure>
      <video src="<?= $video->url() ?>" alt="<?= $page->title()->html() ?>" />
    </figure>
  <?php endforeach ?>

But as you can see, the video will only show at the end after all images because im looping for them seperately. How can loop the content and show image or video depending on whats in the loop.

Loop through all files.

  <?php
  foreach($page->files()->sortBy('sort', 'asc') as $file): ?>
    <?php if($file->type() == 'image'): ?>
      <figure>
        <img src="<?= $file->url() ?>" alt="<?= $page->title()->html() ?>" />
      </figure>
    <?php endif ?>
    <?php if($file->type() == 'video'): ?>
       <figure>
         <video src="<?= $file->url() ?>" alt="<?= $page->title()->html() ?>" />
      </figure>
   <?php endif ?>
  <?php endforeach ?>
1 Like

Ah thanks! haha i initially tryied to loop through all ‘content’ instead and didnt work. ‘files’ it is then.

by the way, when i used the code you had provided, i got an error.
instead i had to add a colon after each of the if statement. is that right?

eg:
instead of
<?php if($file->type() == 'image') ?>

i used:
<?php if($file->type() == 'image'): ?>

Just testing your PHP skills :wink:

No, of course, sorry, corrected above…

1 Like