Preprocessing data and PHP
Frequently, you want to modify or create variables before they reach the template. You can do this within the theme’s themename.theme
file. This is a pure PHP file in which you can use hooks to do so.
To find the hook that you’re looking for, enable theme debugging at /admin/config/development/settings
. When you inspect the markup for the template, you’ll see THEME HOOK
.
Figure 19.6 – An example of a theme hook in the rendered markup
In the preceding screenshot, the hook is node
.
To make use of this, you can create a function called themename_preprocess_node
within your theme’s themename.theme
file. It takes an array as a parameter, $variables
. This array contains all the variables that are available in the template:
/** * Implements hook_preprocess_HOOK() for node.html.twig. */ function themename_preprocess_node(&$variables) { // Create an additional variable for...