Adding 'active' class to a menu filter

Hello,

New user here, enjoying Kirby A LOT so far.
I tried to search in the forum for my issue, but couldn’t find a solution that works, so I’ll post my code.

I’m using the “restaurant menu” structure and controller and trying to adapt it to fit an old static site I had for a client, here is the code:

    <?php
        $index = $page->categories();
    ?>

<section class="menu menu-3 pad-small-menu">
    <div class="tabbed-menu offix">
        <div class="row">
            <div class="small-11 medium-11 medium-centered columns text-center">
                
                <ul class="menu-filters">
                    <?php foreach ($categories as $category): ?> 
                        <li data-menu-type="<?= $category ?>" class="<?= $index->is($index->first()) ? 'active' : '' ?>" ><span><?= $category ?></span></li>
                    <?php endforeach ?>
                </ul>
            </div>
        </div>

I just need to add the ‘active’ on the first category when the page is loaded.
with the code I just posted, it just put and ‘active’ class to every category and I can’t figure it out.

Thanks in advance for your help.

I’m a bit confused here, why are there two variables $index and $categories?

How is $categories defined, presumably something like

$categories = $page->categories()->split();

$index is then just a field object, so not useful here.

Assuming that my assumption is right:

    <div class="row">
            <div class="small-11 medium-11 medium-centered columns text-center">
                
                <ul class="menu-filters">
                    <?php foreach ($categories as $category): ?> 
                        <li data-menu-type="<?= $category ?>" class="<?= $category === reset($categories) ? 'active' : '' ?>" ><span><?= $category ?></span></li>
                    <?php endforeach ?>
                </ul>
            </div>
        </div>

I.e. compare the currrent element in the loop to the first item in the $categories array.

1 Like

Hello,

my $categories was defined in a controller, like the exemple in your doc:

<?php
return function () {
    $categories = [
        'Plats',
        'Salades',
        'Pasta',
        'Vegan',
        'Desserts'
    ];
    return [
        'categories' => $categories
    ];
};

For some reason when I tried to use $categories without using the $index variable, I had an error message, but somehow, your code works perfectly.

You saved my day :slight_smile:
Thank you so much for your fast answer, nice community.

Have a good day