On this page
Preprocessing and modifying attributes in a .theme file
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:
- Create or edit a file in your theme directory called
mytheme.theme - 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 forpage.html.twigyou createmytheme_preprocess_page. To create a hook fornode--article.html.twigyou createmytheme_preprocess_node__article(replacing dashes with underscores). To discover hook names, see Locating Template Files with Debugging. - Write your changes and save
- Rebuild the cache so your changes are available (if you have Drush installed,
drush cron 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.phpfile. That file has been replaced bymytheme.theme. However, it still functions in much the same way, allowing for hooks to modify output.
Other helpful links
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.