isHomePage in header.php snippet only works once

So I’m trying to check if the current page is the home page. This works quite nice in my header.php snippet, when I try to check if it is the home page and show a different <title> if it isn’t. Now I’d like to show a different banner in the same snippet and check for $page->isHomePage() again. But this time, it seems to be false all the time. Here my snippet:

<?php

/** @var Kirby\Cms\App $kirby */
/** @var Kirby\Cms\Site $site */
/** @var Kirby\Cms\Page $page */
/** @var Kirby\Cms\Pages $pages */
?>

<!DOCTYPE html>
<html lang="de">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="theme-color" content="#B10000">

    <?php if ($page->isHomePage()) : ?>
        <title><?= $site->title()->upper() ?></title>
    <?php else : ?>
        <title><?= $page->title() ?> | <?= $site->title()->upper() ?></title>
    <?php endif; ?>

    <link rel="preload" href="/assets/fonts/Roboto-Regular.woff2" as="font" type="font/woff2" crossorigin>
    <link rel="preload" href="/assets/fonts/Roboto-Medium.woff2" as="font" type="font/woff2" crossorigin>
    <link rel="preload" href="/assets/fonts/Roboto-Bold.woff2" as="font" type="font/woff2" crossorigin>
    <link rel="favicon" href="/favicon.ico">

    <?= css('/assets/css/fonts.css') ?>
    <?= css('/assets/dist/site.css') ?>
</head>

<body>

    <header id="header">
        <div class="wrapper  flex">
            <p><?= $site->title() ?></p>

            <button type="button" aria-label="Menu" aria-controls="navigation" id="hamburger">
                <span></span>
                <span></span>
                <span></span>
            </button>
        </div>
    </header>

    <nav id="nav">
        <div class="wrapper  grid">
            <ul>
                <?php foreach ($pages->listed() as $page) : ?>
                    <li <?php e($page->isOpen(), ' class="is-open"') ?>>
                        <a href="<?= $page->url() ?>"><?= $page->title() ?></a>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    </nav>

    <?php if ($page->isHomePage()) : ?>
        yes, is home
    <?php else : ?>
        nope
    <?php endif; ?>

I always get nope, no matter if it is the home page actually or not. When I call the same function from the template itself, it works. tldr; call to $page->isHomePage() only works once.

That happens because you are using the $page variable inside your foreach loop in the nav. After running this loop, $page is set to the last page in this loop.

Never use Kirby’s $page variable for any other purposes to prevent such issues.

1 Like