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, but if you want to make theme-independent markup it is better to code a custom module.

To work with preprocess functions:

Create or edit a file in your theme directory called mytheme.theme

Create a function such as mytheme_preprocess_HOOK where HOOK refers to the item you wish to affect.

Write your changes and save

Rebuild the cache so your changes are available (if you have drush installed, drush cr on the command line)

Let's assume we wanted to add a class of my-menu to all of the menus on your site. Assuming your theme is called "mytheme" you would write the following function:

/**
* Implements hook_preprocess_HOOK() for menu.html.twig.
*/
function mytheme_preprocess_menu(&$variables) {
// If there is not an existing class array, create an empty array.
if (!isset($variables['attributes']['class'])) {
$variables['attributes']['class'] = [];
}
// Merge with any classes that may have been set by other hook_preprocess_menu invocations
$variables['attributes']['class'] = array_merge($variables['attributes']['class'], ['my-menu']);
}

This is very similar to Drupal 7 and helps if you want to target a specific menu as well.

You could inspect the $variables object with a condition to determine which menu you are working with. The elements within $variables become available in twig after theme preprocessing.

So now to extend our example, let's assume we want to add the class "my-main-menu" to the main menu of your site. This would be the function to do so: