Introduce a generic ThemeSwitcher service to standardize theme context switching

Created on 4 April 2025, 20 days ago

Problem/Motivation

Currently, modules that need to temporarily switch the active theme must implement their own utility logic. For example, the search_api module includes a ThemeSwitcher class to temporarily change the theme during render or search processing.

This results in code duplication and a lack of standardization across contrib modules that need similar functionality.

Drupal core already includes a similar utility pattern in the form of AccountSwitcher, which provides a structured and reliable way to switch user accounts during execution. A parallel service for switching themes would be similarly valuable.

Steps to reproduce

1. Implement logic in a custom or contrib module that needs to temporarily switch the active theme.
2. Observe that core does not provide a reusable service to handle theme switching.
3. Review how modules like search_api solve this by duplicating utility logic.

Proposed resolution

Introduce a ThemeSwitcher service in Drupal core that:
- Follows a similar structure and behavior to AccountSwitcher.
- Provides public methods such as switchTo() and restoreOriginalTheme(), or scoped switching via closures.
- Can be injected as a service into classes that need to perform temporary theme switches.

This service should encapsulate all theme switching logic, ensure proper restoration, and be documented for contrib use.

Remaining tasks

- Define the interface and service definition for the new ThemeSwitcher.
- Add functional tests to validate theme context switching and restoration.
- Document usage with examples in the CHANGELOG or relevant core docs.
- Audit existing contrib modules for similar patterns and suggest usage of the new service once available.

User interface changes

None.

API changes

- Introduction of a new ThemeSwitcher service.
- No changes to existing APIs expected.

Data model changes

None.

Feature request
Status

Active

Version

11.0 🔥

Component

theme system

Created by

🇪🇸Spain eduardo morales alberti Spain, 🇪🇺

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024