Themes can be simple to compose, sometimes containing a single configuration file, a couple of Twig templates, and a few assets. However, there will be times when we need to intercept and override variables and data that Drupal outputs before them reaching our Twig templates. Drupal's API (https://api.drupal.org/api/drupal/8) allows us to create a *.theme
file where we can add theme functions that can hook into the API using different types of function calls.
The main role of preprocessor functions is to prepare variables to be used within our Twig templates using template_preprocess
functions. These functions reference the theme and template we want to intercept. We would write an example of intercepting the html.html.twig
template variables used within our Twig theme as follows:
twig_preprocess_html(&$variables) { }
With this simple function call, we can hook into the theme preprocessing to intercept the $variables
argument and manipulate it as needed before our template receives the variables. In order for us to use this function, we need to do the following steps:
twig.theme
file within the themes/twig
folder. The twig.theme
file will contain all the PHP functions we will write to work with Drupal's API.twig.theme
file and then save the file as:<?php /** * Implements hook_preprocess_html(). */ function twig_preprocess_html(&$variables) { // add to classes $variables['attributes']['class'][] = 'twig'; }
Whenever we add a file or template for the first time, we will need to clear the Drupal cache.
Now that we have created our twig.theme
file and have the outline of our first preprocess hook, let's take a look at how to override a variable. Previously, we saw that Drupal was adding classes to our body tag using the $attributes
variable. But what if we want to add additional classes specific to our theme?
Open twig.theme
and edit the preprocess function to include the following:
/** * Implements hook_preprocess_html(). */ function twig_preprocess_html(&$variables) { // add to classes $variables['attributes']['class'][] = 'twig'; }
Now if we save our twig.theme
file and refresh the browser, we will see that our class is added, as shown in the following image.
While we have only touched the surface of the functionality that we can use when theming, we are purposely not going into depth regarding all the API calls that we have access to with Drupal 8. If you are interested in taking a deeper look, you can find the reference at https://api.drupal.org/api/drupal/8.
One last thing to note is that we can reference the completed exercise files for Chapter 3, Dissecting a Theme, if we need to compare any of the work we just completed or perform a database restore.
18.118.226.66