Skip to content

Instantly share code, notes, and snippets.

@wiratama
Forked from jimconte/ThemeNegotiator.php
Created April 4, 2019 02:40
Show Gist options
  • Save wiratama/b87527b6150ea39daa0a3b19fba249f2 to your computer and use it in GitHub Desktop.
Save wiratama/b87527b6150ea39daa0a3b19fba249f2 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment