Skip to content

Instantly share code, notes, and snippets.

@andriyun
Last active November 22, 2022 19:56
Show Gist options
  • Save andriyun/f0902d5dcf7c8d5ffe9e1eb3f9531018 to your computer and use it in GitHub Desktop.
Save andriyun/f0902d5dcf7c8d5ffe9e1eb3f9531018 to your computer and use it in GitHub Desktop.
Drupal 8 switch active theme programmatically
<?php
/**
* See original implementation http://cgit.drupalcode.org/mailsystem/tree/src/MailsystemManager.php#n60
*/
// Switch the theme to the configured mail theme.
$theme_manager = \Drupal::service('theme.manager');
$mail_theme = '[your theme name]';
$current_active_theme = $theme_manager->getActiveTheme();
if ($mail_theme && $mail_theme != $current_active_theme->getName()) {
$theme_initialization = \Drupal::service('theme.initialization');
$theme_manager->setActiveTheme($theme_initialization->initTheme($mail_theme));
}
try {
// Do your actions here.
// .....
}
finally {
// Revert the active theme, this is done inside a finally block so it is
// executed even if an exception is thrown during sending a mail.
if ($mail_theme != $current_active_theme->getName()) {
$theme_manager->setActiveTheme($current_active_theme);
}
}
@augustofagioli
Copy link

Thanks for sharing.
Will give a try to this for my pages where an alternative theme is needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment