Theme Negotiators - Switch theme dynamically

Submitted by editor on Sun, 10/30/2016 - 17:02
Question

How to Switch theme dynamically on drupal 8 , using theme negotiators ?

Create a custom module (here : example)

For active themes by route you first have to define a service in your $module.services.yml file:

On example.services.yml

Add:

services:
  theme.negotiator.example:
    class: Drupal\example\Theme\ExampleNegotiator
    tags:
      - { name: theme_negotiator, priority: 0 }

and then use that new defined service class:
Create a class ExampleNegotiator on example/src/Theme With:

namespace Drupal\example\Theme;

use Drupal\Core\Theme\ThemeNegotiatorInterface;
use Drupal\Core\Routing\RouteMatchInterface;

class ExampleNegotiator implements ThemeNegotiatorInterface {
  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    // Use this theme on a certain route.
    return $route_match->getRouteName() == 'example_route_name';
  }

  /**
   * {@inheritdoc}
   */
  public function determineActiveTheme(RouteMatchInterface $route_match) {
    // Here you return the actual theme name.
    return 'stark';//The theme name
  }
}

 

Add new comment