Preprocessing and modifying attributes in a .theme file

Last updated on
1 June 2023

This documentation needs work. 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 make theme-independent markup you should add code to a custom module, where in place of mytheme.theme  you have mymodule.module.

For the purposes of documentation here "mytheme" is the machine name of your theme; for example "bartik" is a theme machine name.

To work with preprocess functions:

  1. Create or edit 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. HOOK names follow twig template suggestions. 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 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) {
  // 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.

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') {
    $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 work

You can: