Last active
May 10, 2022 11:24
-
-
Save jimconte/bc0b8c7a3ec938f43284d178dd109af0 to your computer and use it in GitHub Desktop.
A sample class implementation of Drupal 8's ThemeNegotiatorInterface from https://jimconte.com/blog/web/dynamic-theme-switching-in-drupal-8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @file | |
* Contains \Drupal\jcmodule\Theme\ThemeNegotiator | |
*/ | |
namespace Drupal\jcmodule\Theme; | |
use Drupal\Core\Routing\RouteMatchInterface; | |
use Drupal\Core\Theme\ThemeNegotiatorInterface; | |
class ThemeNegotiator implements ThemeNegotiatorInterface { | |
/** | |
* @param RouteMatchInterface $route_match | |
* @return bool | |
*/ | |
public function applies(RouteMatchInterface $route_match) | |
{ | |
return $this->negotiateRoute($route_match) ? true : false; | |
} | |
/** | |
* @param RouteMatchInterface $route_match | |
* @return null|string | |
*/ | |
public function determineActiveTheme(RouteMatchInterface $route_match) | |
{ | |
return $this->negotiateRoute($route_match) ?: null; | |
} | |
/** | |
* Function that does all of the work in selecting a theme | |
* @param RouteMatchInterface $route_match | |
* @return bool|string | |
*/ | |
private function negotiateRoute(RouteMatchInterface $route_match) | |
{ | |
$userRolesArray = \Drupal::currentUser()->getRoles(); | |
if ($route_match->getRouteName() == 'user.login') | |
{ | |
return 'seven'; | |
} | |
elseif ($route_match->getRouteName() == 'some.other.route') | |
{ | |
return 'some_other_theme'; | |
} | |
elseif (in_array("administrator", $userRolesArray)) | |
{ | |
return 'seven'; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Code looks clean and good. But be aware that this way is negotiateRoute() called twice, which is not good.