Skip to content

Instantly share code, notes, and snippets.

@jimconte
Last active May 10, 2022 11:24
Show Gist options
  • Save jimconte/bc0b8c7a3ec938f43284d178dd109af0 to your computer and use it in GitHub Desktop.
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
<?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;
}
}
@bulrych
Copy link

bulrych commented May 10, 2022

Code looks clean and good. But be aware that this way is negotiateRoute() called twice, which is not good.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment