13

In Drupal 8, is there a way to figure out what theme you are currently using in a module? I need to get the name programmatically within the code of a module.

0

3 Answers 3

33

Using the theme manager is the proper Drupal 8 way of getting information about your theme.

\Drupal::service('theme.manager')->getActiveTheme()

A general rule in drupal 8 is look for the manager (/handler) service.

** Note: as Neograph734 pointed out, \Drupal::service('theme.manager')->getActiveTheme() will return the active theme object. If you want to get the theme machine-name then use \Drupal::service('theme.manager')->getActiveTheme()->getName()

1
  • 5
    Note that the actual theme name can be derived from the ActiveTheme with getName(). So to get the theme name one would use \Drupal::service('theme.manager')->getActiveTheme()->getName(); Sep 12, 2017 at 15:00
6

This will do it:

$config = \Drupal::config('system.theme');    
print $config->get('default');

You can always use drush to explore your available configs:

drush config-list

and

drush config-list system

gave me a list:

...
system.rss
system.site
system.theme.global
system.theme
...

and then I could check with the following:

drush cget system.theme.global

and

drush cget system.theme

to finally find out that it holds a default property that was what you asked for.

2
  • 4
    This answers returns the default theme. The OP asked for the current theme, and the accepted answer returns current theme. Normally it won't matter, but if there is a module that dynamically selects a theme depending on page/domain/user etc then the difference is important.
    – AdamS
    Jun 8, 2017 at 11:19
  • 1
    True, if there is a custom theme negotiator in play, the results will differ. If not, then the getActiveTheme() function will end up returning exactly the same: $this->configFactory->get('system.theme')->get('default') Jun 9, 2017 at 13:12
4
  1. if you want to get actual active theme name administration theme included Use :

 $activeThemeName = \Drupal::service('theme.manager')->getActiveTheme(); 

  1. if you want your default selected theme theme used in front not admistartion theme Use :

 $defaultThemeName = \Drupal::config('system.theme')->get('default');    

Not the answer you're looking for? Browse other questions tagged or ask your own question.