9

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.

23

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()

| improve this answer | |
  • 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(); – Neograph734 Sep 12 '17 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.

| improve this answer | |
  • 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 '17 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') – Stefanos Petrakis Jun 9 '17 at 13:12
2
  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');    

| improve this answer | |

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