Switching template in a router

I try to display a page with a different template depending on the value of a field (by that I mean a different templates/mytemplate.php, not a different blueprint). How can I do that?
Specifically, if the URL begins with a year and this is the “active year” I’d like to display the page differently.

In the router I tried something like:

if ($year == page('editions')->active_edition()) {
  tpl::load( kirby()->roots()->templates() . DS . 'active-edition.php' );
}

But it doesn’t work. Not quite sure tpl::load requires more arguments.

Any specific reason why you try to use templates instead of snippets?

Not sure what you mean? The whole layout is different, not just a tiny part of it.
Or do you mean putting the whole template code inside snippets, and in the template itself only keep an if statement to load them? Hadn’t thought about that :upside_down:

Yes that’s what I meant sorry for not being clear.

It will make things definitely easier, since you don’t have to pass all the variables to the template.

That’s indeed much simpler! Thank you, both of you :slight_smile:
If anyone ever has the same need, in my template the switch looks like this:

$year = date('Y', strtotime( $page->content()->date() ) );

if ( $year == page('editions')->active_edition() ) {
  snippet('edition-active');
}
else {
  snippet('edition');
}
2 Likes

Thanks for sharing your solution.
You could also get your date in a simpler way:

$year = $page->date('Y');

https://getkirby.com/docs/cheatsheet/page/date

Ah good point, thanks!
It didn’t work initially, because I use strftime. So I needed:

$year = $page->date('%Y');
1 Like