Use a controller from a snippet

Hello all,

I would like to know if there is a way to link a controller and a snippet.

In many of my page there is a banner that is add with a snippet, but there is some logic in this snippet (for example to provide fallback solutions when no banner is found for the page). Do there is a way to link a controller to this snippet ?

Shared controller is an option but it would force me to have one controller per page that, for the majority would just call the shared controller that made the logic work for the banner.

Thanks in advance

Could you post the snippets content? might be another way to hande it.

Yup

<?php
	$imgBanner = $page->image('banner.jpg');
	if ($imgBanner)
		$urlBanniere = $imgBanner->url();
	else
		$urlBanniere = $default;

	$description = $page->description();
	if ($description->isEmpty())
		$description = "<br/>";
?>

<header id="banner" class="text-white text-center mb-12 shadow-lg shadow-gray-600 bg-blue-800 bg-no-repeat bg-center bg-cover"
        style="background-image: url('<?= $urlBanner ?>')">
	<div class="backdrop-brightness-50">
		<div class="max-w-6xl mx-auto px-6 py-12 lg:py-32 space-y-4 flex flex-col items-center">
			<h1 class="text-4xl"><?= $page->title() ?></h1>
			<span class="bg-rose-500 w-10 h-[0.20rem]"></span>
			<p class="text-xl"><?= $description ?></p>
		</div>
	</div>
</header>
<div class="max-w-6xl mx-auto p-6">

$default is an url passed in snippets parameters

<?= snippet('base/banner', ['defaut' => url('assets/images/default_banner.jpg')]) ?>

Ty

If you place your logic inside the site.php controller you don’t need to have an extra controller for each page just to bring in the shared content.

If your template doesn’t have a controller set it will automatically fallback on the site.php one if present.

You only need to use the shared controller solution if you need both shared/global content AND template specific content. it’s only in that case that you need to merge the two.

This is an example from the starter kit.
As you can see the $banner variable coming from the site.php controller is available within the home.php template because the starter kit doesn’t have an home.php controller.

2 Likes

Ooh I didn’t know for the site.php controller, that seems to be exactly what i needed, thanks :smiley:

Do keep in mind that if you need a controller for a specific template you will have to merge the two (Shared Controllers | Kirby CMS) otherwise the site.php controller will get ignored.

Yep just tried it :smile: thanks.