Using Preprocessor Plugins In Themes

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:

Preprocessor Plugins

Allows developers to create Plugins to preprocess templates instead of hook functions.

Preprocessor Plugins grants developers the ability to create Plugins to house preprocessing logic for templates. They are a replacement and alternative to hook_preprocess_HOOK() functions.

Basic Usage Guide

Take this traditional hook function as an example. You would normally put this in a .theme file to add the foo variable to the node.html.twig template.

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

With Preprocessor Files, you can instead put the preprocessing logic in a standalone file.

Preprocessor Files

Allows developers to create dedicated files to preprocess templates instead of hook functions.

Preprocessor Files grants developers the ability to create dedicated files to house preprocessing logic for templates. They are a replacement and alternative to hook_preprocess_HOOK() functions.

Preprocessing and modifying attributes in a .theme file

Just like Drupal 7, you can affect the output of certain HTML via preprocess functions. For example, if you wanted to add a class to a menu and preferred to do this at the PHP level, you can. This is a good way to alter theme-specific markup. If you want to add or edit theme-independent markup, you should create a custom module instead.

Subscribe with RSS Subscribe to RSS - preprocessor