Checking the file type in order to apply different markup?

Is there a way for me to write an if-statement that checks the type of whatever file is pulled?

I’d like to pull all files from a page and apply different markup to images and videos. Here’s my current code, which pulls all the files but only contains markup-application suited to images:

<div class="slider-container" id="slider#1">
	<div class="slider">

		<?php foreach($page_files->sortBy('sort', 'asc') as $page_file): ?>

			<div  style="background: url('<?= $page_file->url() ?>'); background-size: cover; height: 100vh;"></div>

		<?php endforeach ?>


I’d like to add an if-statement within the foreach-loop to make a distinction between images and videos. I can probably use $file->type() to do so? How would the full statement have to look like? Something like this?:

<?php if() $page_file->type() = 'jpg' { ?>

	<!-- apply markup -->
<?php endif; ?>

It’d be awesome if someone could help me out. Thanks in advance for all help.

<?php if($file->type() == 'image'): ?>
  <!-- markup for image -->
<?php endif ?>
<?php if($file->type() == 'video'): ?>
  <!-- markup for video -->
<?php endif ?>

$file->type() returns a file type like image, video, document etc., not an extension.

1 Like

You can filter on the extension though, useful if you wanted to add filetype icons, or something to a download list… i did it this way in one of my projects, but maybe theres a slicker way… works though.

<?php foreach($page->documents()->filterBy('extension', 'pdf') as $pdf): ?>
<li><a href="<?= $pdf->url() ?>"><i class="fa fa-file-pdf-o" aria-hidden="true"></i><?= $pdf->filename() ?> (<?= $pdf->niceSize() ?>)</a></li>
<?php endforeach ?>

<?php foreach($page->documents()->filterBy('extension', 'doc') as $doc): ?>
<li><a href="<?= $doc->url() ?>"><i class="fa fa-file-word-o" aria-hidden="true"></i><?= $doc->filename() ?> (<?= $doc->niceSize() ?>)</a></li>
<?php endforeach ?>

Just add more as required. Sorry if that isnt quite what you want, not sure what your intended use case is.

If you wanted to do more then one and give them the same icon, this would do it:

<?php foreach($page->documents()->filterBy('extension', 'in',  ['png', 'gif', 'jpg']) as $img): ?>
<li><a href="<?= $img->url() ?>"><i class="fa fa-file-png-o" aria-hidden="true"></i><?= $img->filename() ?> (<?= $img->niceSize() ?>)</a></li>
<?php endforeach ?>

That would make sense if you wanted to group them, not if you want to display them in the order they appear.