Load snippet based on parent page slug/title

I need to display a different layout based on current pages parent. I’ve tried doing this to load different snippets or to reduce having multiple files load different code within one snippet.

    <?php if($page->parent()->title() == 'News'):
    // Include the News Article HERO snippet if viewing a news article ?>
        <?= snippet('global.hero.news') ?>
        <?php else: ?>
        <?= snippet('global.hero') ?>
    <?php endif ?>

This works perfectly fine until you view a page that has siblings but no parent:

Home > Solutions

Kirby then returns an an error in debug mode:

Error. Call to a member function title() on null

I am using this also for adding a different class name to the body tag:

<?php if($page->parent()->slug() == 'news'): ?>
<body class="hero-<?= $page->parent()->slug() ?>">
	<?php else: ?>
<body class="hero-<?= $page->uid() ?>">
<?php endif ?>

With the same results, works fine until a page that has siblings but no parent, the call to member function error.

Any ideas?

You should always check if a method like parent returns a page object, also, you can check if a page has a parent, either with $page->depth() or with $page->parents()->count().

Thank you for your guidance… this is what I’ve now got working:

<?php if( $page->parents()->count() == 2 ): // Only second Level Parent /media-centre/news/article ?>
	<?php if($page->parent()->slug() == 'news'): ?>
	<body class="hero-<?= $page->parent()->slug() ?>">
	<?php endif ?>
<?php endif ?>

<?php if( $page->parents()->count() <= 1 ): // First level Parent or less /about-us/about ?>
	<body class="hero-<?= $page->uid() ?>">
<?php endif ?>

Your logic can be written a bit shorter:

<?php
$bodyClass = $page->parents()->count() === 2 && $page->parent()->slug() === 'notes' ? 'hero-' . $page->parent()->slug() : 'hero-' . $page->uid(); 
?>
<body class="<?= $bodyClass ?>">

Thank you… still learning Kirby but really impressed so far. My shorter code will come later just need to understand to get it working first :slight_smile: