Contextual/conditional snippets

I often run into situations where I’d only like to call a snippet if I’m in the correct page content:

<?php if ($page->is('home')): ?>
    <?=snippet('modules/index-children')?>
<?php endif?>

This is not very readable as soon as there are multiple consecutive conditions. So before reinventing the wheel, is there something like a contextual snippet mode? Like:

<?=contextualSnippet($page->is('home'), 'modules/index-children')?>

Or:

<?=snippetWhen('home', 'modules/index-children')?>

No, but you can create your own helpers…

What is the appropriate way to do this?

Create a plugin with your custom helper(s), e.g. /site/plugins/helpers/index.php. In this index.php, define your custom helpers (just normal PHP functions).

Something like (very basic example):

function snippetWhen($uid, $snippet) {
  if ($page->is($uid)) {
    echo snippet($snippet);
  }
}
1 Like

Alright, I was somehow trying to put that into Kirby::plugin. Thanks!

The plugin wrapper is only needed/useful if you extend core functionality, i.e. page/file/site methods, blueprints, components etc.

Yes, I was complicating things … :slight_smile:

So this is my solution:

function snippetWhen($snippet, $condition, $expected = true)
{
    if (is_string($condition)) {
        $condition = page()->is($condition);
    }

    if ($condition === $expected) {
        echo snippet($snippet);
    }
}

Usage:

// echo snippet if page is home
<?=snippetWhen('services', 'home')?>

// echo snippet if page is project
<?=snippetWhen('services', 'project')?>

// echo snippet if page is not home
<?=snippetWhen('children', 'home', false)?>

// echo snippet if condition is true
<?=snippetWhen('children', 36 / 6 === 6)?>
1 Like