Displaying an image with specific filename from a template

I’m creating my own project page, and each project will have a primary hero image. I’m naming them all with “-hero” at the end of them (projectA-hero.jpg, projectB-hero.jpg, etc), but not sure how I’m supposed to be writing the PHP to load that.

This is the full code of my project page template:

<?php snippet('header') ?>

<h2><?php echo $page->title()->html() ?></h2>
<?php $heroimage = $page->files()->filterBy('filename', '*=', '-hero'); ?>
<img class="projecthero" src="<?php echo $heroimage->url(); ?>" alt="<?php echo $page->title()->html() ?>" >
<section class="projectdescription">
  <?php echo $page->text()->kirbytext() ?>
</section>

<?php snippet('footer') ?>

However this seems broken because nothing else loads after the h2. Help would be appreciated.

EDIT: OK I was using a $project variable which wasn’t on here so I reverted it to $page and it “unbroke” the page but the image still isn’t appearing. I just get the alt text and the src appears empty.

Hi,

filterBy gives you a collection of files (which contains only one file in your case) and your can select the first (or single) file with first(). So

$heroimage = $page->files()->filterBy('filename', '*=', '-hero')->first();

should work.

Hmmm, that didn’t work. Something isn’t right with the PHP, it’s back to its broken state.

Where I’m at right now:

<h2><?php echo $page->title()->html() ?></h2>
<?php $heroimage = $page->files()->filterBy('filename', '*=', '-hero')->first(); ?>
<img class="projecthero" src="<?php echo $heroimage->url(); ?>" alt="<?php echo $page->title()->html() ?>" >
<section class="projectdescription">
  <?php echo $page->text()->kirbytext() ?>
</section>

The code looks alright to me. Are you sure the image is in the correct folder? Have you turned on debugging in your config.php? Or do you get any error messages in your server’s php log files?

[groaannnnnnnnnnnnnnn]

It was in fact in the correct folder, but I didn’t have a hyphen in the filename. So yeah, the code works perfectly fine. Thanks a bunch!