Using Preprocessor Plugins In Themes

Last updated on
29 March 2025

Overview

Let's take a look at a quick comparison between a traditional preprocess function and a preprocessor plugin.

Traditionally, you would preprocess a node.html.twig template using the following code:

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

To achieve the same functionality as above within your theme with a Plugin, you would do the following:

Create a MY_THEME.preprocessors.yml file at the root of your theme with the following contents:

MY_THEME.preprocessor.node:
  class: '\Drupal\MY_THEME\Plugin\preprocessors\NodePreprocessor'
  hooks:
    - node
  weight: 0

Plugins can only be discovered in themes via YAML discovery. This is why the above file is created.

Following this, create a file at MY_THEME/src/Plugin/preprocessors/NodePreprocessor.php with the following content.

<?php

namespace Drupal\MY_THEME\Plugin\preprocessors;

use Drupal\preprocessors\PreprocessorPluginBase;

/**
 * Provide plugin to preprocess variables for nodes.
 */
final class NodePreprocessor extends PreprocessorPluginBase {

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

}

With the above done, you should have a functional preprocessor plugin! Any code within the ::preprocess() method is equivalent to code you would have in a traditional hook_preprocess_HOOK() function. You can create plugins and migrate your code without much hassle.

Help improve this page

Page status: No known problems

You can: