Advertising sustains the DA. Ads are hidden for members. Join today

Basic Usage Guide

Last updated on
12 December 2023

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.

By default, preprocessor files are loaded from YOUR_THEME/preprocessors. Files named THEME_HOOK.preprocessor.php are loaded and treated as preprocess functions.

THEME_HOOK here refers to the theme hook you are preprocessing, or in other words the HOOK part in a hook_preprocess_HOOK() function.

Below is an example file that would preprocess a node.html.twig template.

YOUR_THEME/preprocessors/node.preprocessor.php

<?php

/**
 * @file
 * Preprocess override for a template. Acts as a preprocess function.
 *
 * Any modifications done in this file are equivalent to doing them within a
 * hook_preprocess_HOOK() implementation.
 *
 * The modifications here execute after traditional hooks if both are
 * implemented.
 *
 * The loading of this file is provided by the Preprocess Files module.
 * @see \Drupal\ppf\PreprocessFiles
 *
 * Available variables:
 * @var array $variables
 *   The variables array. The same you would get from a traditional preprocess
 *   hook function.
 * @var string $hook
 *   The theme hook.
 * @var array $info
 *   The info array.
 */

// Preprocess your variables here just like you would in a hook!
$variables['foo'] = 'bar';

The snippet here is equivalent to the traditional hook above.

What this provides is the ability to segment your code and have it be more organized.

The same steps can be used to create Preprocessor Files in your custom modules. They are loaded from YOUR_MODULE/preprocessors.

Help improve this page

Page status: No known problems

You can: