Modifying attributes in a .theme file

Last updated on
30 November 2016

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.

  1. Create a file in your theme directory called mytheme.theme
  2. Create a function such as mytheme_preprocess_HOOK where HOOK refers to the item you wish to affect.
  3. Write your changes and save
  4. Rebuild the cache so your changes are available

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. 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:

/**
* Implements hook_preprocess_HOOK() for menu.html.twig.
*/
function mytheme_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'main') {
    if (!isset($variables['attributes']['class'])) {
      $variables['attributes']['class'] = [];
    }
    $variables['attributes']['class'] = array_merge($variables['attributes']['class'], ['my-menu']);  }
}

Differences from Drupal 7

  • There is no longer a template.php file. That file has been replaced by mytheme.theme. However, it still functions in much the same way allowing for hooks to modify output.

Other helpful links

A search through the API of preprocess implementations in core.
hook_preprocess_HOOK API documentation