Published in Drupal 11.3.x
Drupal 11.3 introduces a significant change in how preprocess functions for Views plugins are handled.
Previously, Drupal would implicitly discover functions like template_preprocess_HOOK() and apply them automatically to corresponding templates. This implicit behavior is now deprecated.
🔍 What Has Changed
- Views plugins can define a
themekey in their plugin annotation. - Earlier, Views would automatically create a theme hook and apply the corresponding
template_preprocess_HOOK()function. - Now, the system expects that an initial preprocess callback is explicitly defined in a specific method of a class, if such a method exists.
🧩 How Initial Preprocess Callbacks Work
The new convention places preprocess callbacks in a theme hooks class. The method name is generated by camel-casing the theme hook:
namespace Drupal\module_name\Hook;
class ModuleNameThemeHooks {
public function preprocessCamelizedThemeHookName(array $variables) {
// Your preprocessing logic here.
}
}
Example:
If the module views_example_display defines a display plugin with:
theme: "views_display_example"
The corresponding initial preprocess method looks like this:
namespace Drupal\views_example_display\Hook;
class ViewsExampleDisplayThemeHooks {
public function preprocessViewsDisplayExample(array $variables) {
// Prepare variables for the template.
}
}
⚙️ Service Registration
- The theme hooks class is automatically registered as a service if it contains at least one hook method.
- You can also register it explicitly in your
services.yml:
services:
Drupal\views_example_display\Hook\ViewsExampleDisplayThemeHooks:
autowire: true
✅ Key Takeaways
- Implicit
template_preprocess_HOOK()functions are deprecated. - Use initial preprocess callbacks in a dedicated theme hooks class.
- This change affects module developers and themers who create custom Views plugins.
- Following this pattern ensures your preprocess logic is compatible with Drupal 12 and beyond.
Comments