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:
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);
}
}
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)?>