Template for links and images breaks with unexpected error

I’m new to Kirby and following Bastian’s How-To on YouTube. https://www.youtube.com/watch?v=QwjX8JAwBws at the time 38:10

I’m gettting great results until in the foreach for my designs.php template adding images breaks with an unexpected error. See my screenshot. I’ve got the design.php template in good shape, the images in the Design folder next to design.txt … but if I remove Line 11 from the foreach, it works with no images.

Any help is very much appreciated!

<?php snippet('masthead') ?>
<h1><?= $page->title() ?></h1>
<?= $page->text() ?>

<ul class="design">
	<?php foreach ($page->children()->listed() as $design): ?>
	<li>
		<a href="<?= $design->url() ?>">
			<?= $design->image()->crop(500) ?>
			<?= $design->title() ?>
		</a>
	</li>
	<?php endforeach ?>
</ul>
<?php snippet('footer') ?>

Hey, welcome to Kirby!

What I see in your screenshot is that your images are in the same folder as the children (art, web etc.).

In your templates foreach loop, however, you loop through these children and try to get the first image of these children. For this to work, each of these children folders needs to have at least one image.

Additionally, once you have put one image into the children, you should nevertheless always check in your code if the image exists, before you call a method like resize, crop, url or any other. Then you will not get such an error even if there is no image:

<?php snippet('masthead') ?> 
<h1><?= $page->title() ?></h1>
<?= $page->text() ?>

<ul class="design">
	<?php foreach ($page->children()->listed() as $design): ?>
	<li>
		<a href="<?= $design->url() ?>">
                        <?php if ( $image = $design->image() ) : ?>
			    <?= $image->crop(500) ?>
                        <?php endif ?>
			<?= $design->title() ?>
		</a>
	</li>
	<?php endforeach ?>
</ul>
<?php snippet('footer') ?>
1 Like

Thank you very much @texnixe!!! That did the trick :slight_smile: