Using Preprocessor Plugins In Modules

Last updated on
29 March 2025

Attribute-based Plugins

Specific version(s)

Attribute-based plugins are only available in Drupal 10.2 or above. Use PHP annotations instead if you cannot use attributes .

Below we will showcase the equivalent of writing the following hook with Attribute-based Plugins:

/**
 * Implements hook_preprocess_HOOK().
 */
function MY_MODULE_preprocess_node(&$variables) {
  $variables['foo'] = 'bar';
}

Create a class at MY_MODULE/src/Plugin/preprocessors/NodePreprocessor.php with the following content:

<?php

namespace Drupal\MY_MODULE\Plugin\preprocessors;

use Drupal\preprocessors\Attribute\Preprocessor;
use Drupal\preprocessors\PreprocessorPluginBase;

/**
 * Provide plugin to preprocess variables for nodes.
 */
#[Preprocessor(
  id: 'MY_MODULE.preprocessor.node',
  hooks: [
    "node"
  ],
  themes: "*",
  weight: 0
)]
final class NodePreprocessor extends PreprocessorPluginBase {

  /**
   * Preprocess your variables.
   *
   * This method works just like a 'hook_preprocess_HOOK()' function.
   *
   * {@inheritdoc}
   */
  public function preprocess(array &$variables, string $hook, array $info) : void {
    $variables['foo'] = "bar";
  }

}

Plugin properties are set within the attribute as seen in the snippet of code.

Annotation-based Plugins

Specific version(s)

If you are working in Drupal 10.2 or newer, use PHP attributes instead of annotations.

Below we will showcase the equivalent of writing the following hook with Annotation-based Plugins:

/**
 * Implements hook_preprocess_HOOK().
 */
function MY_MODULE_preprocess_node(&$variables) {
  $variables['foo'] = 'bar';
}

Create a class at MY_MODULE/src/Plugin/preprocessors/NodePreprocessor.php with the following content:

<?php

namespace Drupal\MY_MODULE\Plugin\preprocessors;

use Drupal\preprocessors\PreprocessorPluginBase;

/**
 * Provide plugin to preprocess variables for nodes.
 *
 * @Preprocessor(
 *   id = "MY_MODULE.preprocessor.node",
 *   hooks = {
 *     "node",
 *   },
 *   themes = "*",
 *   weight = 0,
 * )
 */
final class NodePreprocessor extends PreprocessorPluginBase {

  /**
   * Preprocess your variables.
   *
   * This method works just like a 'hook_preprocess_HOOK()' function.
   *
   * {@inheritdoc}
   */
  public function preprocess(array &$variables, string $hook, array $info) : void {
    $variables['foo'] = "bar";
  }

}

Plugin properties are set within the class annotation as seen in the snippet of code.

Using YAML Discovery

YAML discovery is an option if you prefer that. To do this, you can follow the same steps outlined in the guide for themes, but instead creating the files in your custom module.

Help improve this page

Page status: No known problems

You can: