Preprocessing and modifying attributes in a .theme file

Last updated on
23 June 2025

This documentation needs review. See "Help improve this page" in the sidebar.

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. If you want to add or edit theme-independent markup, you should create a custom module instead.

The examples here will use "mytheme" as the machine name of your theme. In practice, if you are building on top of the Bartik theme, "bartik" is the theme machine name.

To create a preprocess function:

  1. Create or edit a file in your theme directory called mytheme.theme
  2. Create a function that uses the following pattern: mytheme_preprocess_HOOK, where HOOK refers to the item you wish to affect. HOOK names follow twig template suggestions. So, to create a hook for page.html.twig you create mytheme_preprocess_page. To create a hook for node--article.html.twig you create mytheme_preprocess_node__article (replacing dashes with underscores). To discover hook names, see Locating Template Files with Debugging.
  3. Write your changes and save
  4. 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 the class 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) {
  // Allow the Attribute Class to deal with adding a css class to this element.
  $variables['attributes']['class'][] = 'my-menu';
}

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 pre-processing.

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') {
    $variables['attributes']['class'][] = 'my-main-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.

Help improve this page

Page status: Needs review

You can: