Reviving this for a slightly different use case. I need to serve a different templates folder based on a certain URL segment. My code goes in site/config.php. In there $input is not available yet. So the logic uses $_SERVER['REQUEST_URI']
/**
* Switch ProcessWire templates directory based on the second URL segment.
* Type the second URL segment as key and the name of the new templates folder as value.
* Example: '/imaging/' maps to 'templates-magazine' folder.
* We use the second segment because the first segment is always the language (en, de, etc.)
*/
$config->templateSegments = array(
'imaging' => 'templates-magazine', // first url segment => templates folder name
// Add other segment => folder mappings here
);
// Check the second URL segment directly from REQUEST_URI
$requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
$path = parse_url($requestUri, PHP_URL_PATH);
$segments = explode('/', trim($path ?: '', '/'));
$firstSegment = $segments[1] ?? null;
if ($firstSegment && isset($config->templateSegments[$firstSegment])) {
$folder = $config->templateSegments[$firstSegment];
$config->urls->templates = "/site/" . $folder . "/";
$config->paths->templates = $config->paths->site . $folder . "/";
}
Works well.
in site/init.php I have a ProcessPageView::execute hook so that PW can find the template file and offer the "View" link in the page edit screen in admin.
$wire->addHookBefore("ProcessPageView::execute", function (HookEvent $event) {
// set templates dir for magazine pages in admin
/** @var Pages $pages */
$pages = wire()->pages;
/** @var PagesRequest $request */
$request = $pages->request();
/** @var Page $page */
$page = $request->getPage();
$editPage = $pages->get(input()->get('id'));
if($page->template == 'admin' && $editPage->template == 'magazine-page') {
/** @var Config $config */
$config = wire()->config;
$folder = 'templates-magazine';
$config->urls->templates = "/site/" . $folder . "/";
$config->paths->templates = $config->paths->site . $folder . "/";
}
});
Not the most elegant implementation, but works. Could have put this in site/templates/admin.php but decided against for separation of concerns reasons.