Drupal - Switch theme by content type

In Drupal 7, it was straight forward possible by implementing hook_custom_theme() in your custom module.

As for Drupal 8, you will need to create a ThemeNegotiator. Link to the respective change record : 'theme callback' and hook_custom_theme() replaced by theme negotiators.

In the applies() function of the class you can apply your logic and return the theme you wish to have in the determineActiveTheme() function.

Note that, you might have to create multiple ThemeNegotiators for multiple conditions.


Thanks AjitS for the info, I've used your answer to write the following working code:

class ThemeNegotiator implements ThemeNegotiatorInterface {
  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    // Use this theme on a certain route.
    $node = $route_match->getParameter('node');
    if (!is_null($node) && $node instanceof \Drupal\node\Entity\Node) {
      return $node->getType() == 'content_type_machine_name';
    }

    // apply default theme
    return false;
  }

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

Tags:

Theming