Blog Sections Open
Switching to Mobile Templates with OnWebPageInit and OnLoadDocumentObject
How to switch templates for mobile visitors in Evolution CMS without fighting the cache layer on every request.
Template switching for mobile devices can become messy very quickly in Evolution CMS if you try to do everything in one event. The cleaner pattern from the donor topic split the work into two plugins: one plugin detects the device and marks the request, while the other swaps the template only when the document is loaded from the database.
That separation is what makes the approach durable.
Step 1: mark mobile requests on every page load
global $modx;
$phoneversion = 0;
session_start();
if (isset($_SESSION['phoneversion'])) {
$phoneversion = $_SESSION['phoneversion'];
} else {
require_once $_SERVER['DOCUMENT_ROOT'].'/assets/libs/mobiledetect/Mobile_Detect.php';
$detect = new Mobile_Detect;
if ($detect->isMobile() && !$detect->isTablet()) {
$phoneversion = 1;
}
$_SESSION['phoneversion'] = $phoneversion;
}
if ($phoneversion == 1) {
$_GET['mobile'] = 'true';
}
This plugin belongs on OnWebPageInit. Its job is only to classify the request and make the cache vary cleanly between mobile and non-mobile output.
Step 2: swap the template only when the document object is loaded
global $modx;
$templateMap = [4 => 16, 7 => 18, 8 => 19, 9 => 20, 11 => 21, 12 => 22];
$templateId = $modx->documentObject['template'];
if (isset($templateMap[$templateId])) {
session_start();
if (!empty($_SESSION['phoneversion'])) {
$modx->documentObject['template'] = $templateMap[$templateId];
}
}
This second plugin belongs on OnLoadDocumentObject. Because it runs when the document is loaded from the database, it lets you build separate cached versions per device type without fighting the parser on every hit.
One important caveat
If you split templates this way, make sure the same TVs are available to both the desktop and mobile template sets. Otherwise the switching logic works, but the content model will not.
Paginating Ditto Output That Uses MultiTV Galleries
How to keep Ditto pagination and MultiTV gallery output in sync on Evolution CMS listing pages.
Keeping Child Menus Expanded for the Active Branch in pdoMenu
How to keep submenu wrappers open for the active branch in pdoMenu without hard-coding separate menu trees.